okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
b0fc432ed
main
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 31Cloudflare's tunnel connects from the same computer, so it too can stay on loopback.""" 32return "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.""" 37found :list [str ]= [] 38try : 39s = socket .socket (socket .AF_INET ,socket .SOCK_DGRAM ) 40s .settimeout (0.2 ) 41s .connect (("10.255.255.255" ,1 ))# no packet is sent; it picks the interface of the default route 42found .append (s .getsockname ()[0 ]) 43s .close () 44except OSError : 45pass 46try : 47import psutil 48for infos in psutil .net_if_addrs ().values (): 49for i in infos : 50if i .family == socket .AF_INET : 51found .append (i .address ) 52except Exception :# noqa: BLE001 53pass 54private = [a for a in dict .fromkeys (found )if _is_private (a )and not a .startswith ("127." )and not a .startswith ("169.254." )] 55return private 56 57 58def _is_private (address :str )-> bool : 59try : 60a ,b = (int (x )for x in address .split ("." )[:2 ]) 61except ValueError : 62return False 63return 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.""" 72explicit = os .environ .get ("STRATA_CLOUDFLARED" ,"" ).strip () 73if explicit : 74return [explicit ] 75name = "cloudflared.exe" if WINDOWS else "cloudflared" 76out :list [str ]= [] 77for d in os .environ .get ("PATH" ,"" ).split (os .pathsep ): 78if d .strip (): 79out .append (str (Path (d .strip ().strip ('"' ))/ name )) 80home = Path .home () 81if WINDOWS : 82env = os .environ 83for root in (env .get ("ProgramFiles" ,r"C:\Program Files" ),env .get ("ProgramFiles(x86)" ,r"C:\Program Files (x86)" )): 84out .append (str (Path (root )/ "cloudflared" / name )) 85if env .get ("LOCALAPPDATA" ): 86out .append (str (Path (env ["LOCALAPPDATA" ])/ "Microsoft" / "WinGet" / "Links" / name )) 87out .append (str (Path (env .get ("ProgramData" ,r"C:\ProgramData" ))/ "chocolatey" / "bin" / name )) 88out .append (str (home / "scoop" / "shims" / name )) 89else : 90for d in ("/usr/bin" ,"/usr/local/bin" ,"/opt/homebrew/bin" ,"/home/linuxbrew/.linuxbrew/bin" ,"/snap/bin" , 91str (home / ".local" / "bin" ),str (home / "bin" )): 92out .append (str (Path (d )/ name )) 93seen :set [str ]= set () 94return [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.""" 99try : 100key = (path ,os .stat (path ).st_mtime ) 101except OSError : 102return None 103if key in _cf_seen : 104return _cf_seen [key ] 105try : 106r = subprocess .run ([path ,"--version" ],capture_output = True ,text = True ,errors = "replace" ,timeout = 10 , 107creationflags = getattr (subprocess ,"CREATE_NO_WINDOW" ,0 )if WINDOWS else 0 ) 108text = (r .stdout or "" )+ (r .stderr or "" ) 109except (OSError ,subprocess .SubprocessError ): 110_cf_seen [key ]= None 111return None 112m = re .search (r"(\d{4})\.(\d{1,2})\.(\d{1,3})" ,text ) 113ok = 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 115return _cf_seen [key ] 116 117 118def _cf_new_enough (version :str )-> bool : 119if not version : 120return True # a custom build with no readable version is not refused 121return 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.""" 126for place in _cloudflared_places (): 127if not os .path .isfile (place )or (not WINDOWS and not os .access (place ,os .X_OK )): 128continue 129version = cloudflared_version (place ) 130if version is not None and _cf_new_enough (version ): 131return {"path" :place ,"version" :version } 132return None 133 134 135def find_cloudflared ()-> str | None : 136info = cloudflared_info () 137return 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 142matching only (it can hold a tunnel token) and is never shown. A failed look is an empty list: it never blocks a tunnel.""" 143out :list [tuple [int ,str ]]= [] 144try : 145if WINDOWS : 146text = subprocess .run (["powershell.exe" ,"-NoProfile" ,"-NonInteractive" ,"-Command" , 147"Get-CimInstance Win32_Process -Filter \"Name='cloudflared.exe'\" | ForEach-Object { \"$($_.ProcessId)`t$($_.CommandLine)\" }" ], 148capture_output = True ,text = True ,errors = "replace" ,timeout = 15 ,creationflags = subprocess .CREATE_NO_WINDOW ).stdout 149for line in text .splitlines (): 150m = re .match (r"(\d+)\t(.*)$" ,line ) 151if m : 152out .append ((int (m .group (1 )),m .group (2 ))) 153else : 154text = subprocess .run (["ps" ,"-axo" ,"pid=,comm=,args=" ],capture_output = True ,text = True ,errors = "replace" ,timeout = 5 ).stdout 155for line in text .splitlines (): 156m = re .match (r"\s*(\d+)\s+(\S+)\s*(.*)$" ,line ) 157if m and re .search (r"(^|/)cloudflared$" ,m .group (2 )): 158out .append ((int (m .group (1 )),m .group (3 ))) 159except (OSError ,subprocess .SubprocessError ): 160return [] 161return [(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.""" 166pat = re .compile (rf"--url[= ]\S*: { int ( port ) } (?:/|\s|$)" ) 167return [pid for pid ,cmd in procs if pat .search (cmd )] 168 169 170def other_tunnel_note (pids :list [int ])-> str : 171return (f"cloudflared is already running for another tunnel (PID { pids [ 0 ] } )." if len (pids )== 1 172else f"cloudflared is already running for other tunnels (PIDs { ', ' . join ( map ( str , pids )) } )." ) 173 174 175def find_tailscale ()-> str | None : 176found = shutil .which ("tailscale" ) 177if found : 178return found 179for guess in ("/usr/bin/tailscale" ,"/usr/local/bin/tailscale" ,"/Applications/Tailscale.app/Contents/MacOS/Tailscale" , 180r"C:\Program Files\Tailscale\tailscale.exe" ): 181if Path (guess ).is_file (): 182return guess 183return None 184 185 186def _run (argv :list [str ],timeout :float = 8.0 )-> str : 187try : 188r = subprocess .run (argv ,capture_output = True ,text = True ,errors = "replace" ,timeout = timeout ) 189return r .stdout or "" 190except (OSError ,subprocess .SubprocessError ): 191return "" 192 193 194def tailscale_status ()-> dict : 195"""{"installed", "running", "ip", "name"}: the tailnet address of this computer when Tailscale is up.""" 196exe = find_tailscale () 197out = {"installed" :bool (exe ),"running" :False ,"ip" :None ,"name" :None } 198if not exe : 199return out 200ip = _run ([exe ,"ip" ,"-4" ]).strip ().splitlines () 201if ip and re .fullmatch (r"\d+\.\d+\.\d+\.\d+" ,ip [0 ].strip ()): 202out ["running" ],out ["ip" ]= True ,ip [0 ].strip () 203try : 204data = json .loads (_run ([exe ,"status" ,"--json" ])or "{}" ) 205name = (data .get ("Self" )or {}).get ("DNSName" ) 206out ["name" ]= name .rstrip ("." )if isinstance (name ,str )and name else None 207except ValueError : 208pass 209return 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 : 228plat = "windows" if WINDOWS else "darwin" if sys .platform == "darwin" else "linux" 229return INSTALL_HELP [tool ][plat ] 230 231 232@dataclass 233class AccessOption : 234kind :str 235label :str 236url :str 237note :str 238ready :bool # the helper it needs is there (or none is needed) 239warn :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.""" 244ips = lan_ips () 245lan = ips [0 ]if ips else None 246cf = find_cloudflared () 247ts = tailscale_status () 248out = [AccessOption ("local" ,"This computer only" ,f"http://127.0.0.1: { port } " , 249"for apps on this computer" ,True )] 250out .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 )) 253out .append (AccessOption ("cloudflare" ,"Cloudflare tunnel" ,tunnel_url or "https://<random>.trycloudflare.com" , 254"from anywhere · cloudflared found" if cf else "cloudflared is not installed" , 255bool (cf ),warn =not cf )) 256if ts ["running" ]: 257out .append (AccessOption ("tailscale" ,"Tailscale" ,f"http:// { ts [ 'name' ] or ts [ 'ip' ] } : { port } " , 258"your Tailscale devices" ,True )) 259else : 260out .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 )) 263return out 264 265 266def option_for (kind :str ,port :int )-> AccessOption : 267return 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.""" 272if kind == "cloudflare" and not find_cloudflared (): 273return "cloudflared is not installed on this computer. " + install_help ("cloudflared" ) 274if kind == "tailscale" : 275ts = tailscale_status () 276if not ts ["installed" ]: 277return "Tailscale is not installed on this computer. " + install_help ("tailscale" ) 278if not ts ["running" ]: 279return "Tailscale is installed but not connected. Run: tailscale up" 280if kind == "lan" and not lan_ips (): 281return "No local network address was found on this computer. Check that it is connected to your network." 282return 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).""" 287base = [f"http://127.0.0.1: { s . port } " ] 288if s .access == "lan" : 289base += [f"http:// { ip } : { s . port } " for ip in lan_ips ()[:1 ]] 290elif s .access == "cloudflare" and tunnel_url : 291base = [tunnel_url ]+ base 292elif s .access == "tailscale" : 293ts = tailscale_status () 294if ts ["running" ]: 295base += [f"http:// { ts [ 'name' ] or ts [ 'ip' ] } : { s . port } " ]+ ([f"http:// { ts [ 'ip' ] } : { s . port } " ]if ts ["name" ]else []) 296return 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.""" 301if WINDOWS and kind in ("lan" ,"tailscale" ): 302return ("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." ) 304return None 305 306 307def new_key ()-> str : 308import secrets 309return "sk-strata-" + secrets .token_urlsafe (24 ) 310 311 312def _config_key (path )-> str | None : 313try : 314key = str (json .loads (Path (path ).read_text (encoding = "utf-8-sig" )).get ("api_key" )or "" ).strip () 315except (OSError ,ValueError ,AttributeError ): 316return None 317return 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 322own config (profile `launch-<name>`), the saved preset's, else the one in the newest launch config. None when there is none; `--new-key` 323and the key button are the only ways to rotate it.""" 324try : 325from strata_control import profiles 326from strata_cli .launch import settings as S ,store 327if name : 328try : 329prof ,_rev = profiles .load ("launch-" + S .slug (name )) 330key = _config_key (prof .get ("source_config" )) 331if key : 332return key 333except Exception :# noqa: BLE001 - no such profile yet 334pass 335preset = store .load (name ,missing_ok = True ) 336if preset and preset .api_key : 337return preset .api_key 338newest ,found = - 1.0 ,None 339for row in profiles .list_profiles (): 340if not row ["id" ].startswith ("launch-" ): 341continue 342source = row .get ("source_config" )# an unreadable profile is listed as {id, error}: skip that row, keep looking 343if not source : 344continue 345key = _config_key (source ) 346if not key : 347continue 348try : 349stamp = Path (source ).stat ().st_mtime 350except OSError : 351continue 352if stamp > newest : 353newest ,found = stamp ,key 354return found 355except Exception :# noqa: BLE001 - never block a launch over the lookup 356return None 357 358 359def mask_key (key :str | None )-> str : 360if not key : 361return "off" 362return key [:10 ]+ "•" * 8 if len (key )> 12 else "•" * 8 363 364 365# ----------------------------------------------------------------------------------------------- the quick tunnel 366 367def _state_dir ()-> Path : 368from strata_control import paths 369d = paths .state_base ()/ "launch" 370d .mkdir (parents = True ,exist_ok = True ) 371return d 372 373 374def _tunnel_state (name :str )-> Path : 375from strata_cli .launch .settings import slug 376return _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 382The 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.""" 384exe = find_cloudflared () 385if not exe : 386return None ,missing_helper ("cloudflare" )or "cloudflared is not installed." 387existing = tunnel_info (name ) 388if existing and existing .get ("url" )and existing .get ("port" )== port : 389return existing ["url" ],"The tunnel was already running." 390running = cloudflared_procs (exclude = (int (existing ["pid" ]),)if existing else ()) 391own = own_tunnel_pids (running ,port ) 392if own : 393return 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." ) 395note = other_tunnel_note ([pid for pid ,_ in running ])if running else "" 396stop_tunnel (name ) 397log = _state_dir ()/ f" { Path ( name ). name } .tunnel.log" 398argv = [exe ,"tunnel" ,"--no-autoupdate" ,"--url" ,f"http://127.0.0.1: { port } " ] 399with open (log ,"wb" )as out : 400kw = ({"creationflags" :subprocess .CREATE_NEW_PROCESS_GROUP | subprocess .CREATE_NO_WINDOW }if WINDOWS 401else {"start_new_session" :True }) 402proc = subprocess .Popen (argv ,stdin = subprocess .DEVNULL ,stdout = out ,stderr = subprocess .STDOUT ,** kw ) 403from strata_control import procs 404token = procs .start_token (proc .pid ) 405url = None 406deadline = time .monotonic ()+ wait 407while time .monotonic ()< deadline and url is None and proc .poll ()is None : 408try : 409m = TUNNEL_URL .search (log .read_text (encoding = "utf-8" ,errors = "replace" )) 410except OSError : 411m = None 412if m : 413url = m .group (0 ) 414break 415time .sleep (0.4 ) 416state = {"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" ) 418try : 419log .write_bytes (b"" )# keep no log text: the address is all anyone needs from it 420except OSError : 421pass 422if url is None : 423stop_tunnel (name ) 424return 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." ) 426return 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 : 430try : 431state = json .loads (_tunnel_state (name ).read_text (encoding = "utf-8" )) 432except (OSError ,ValueError ): 433return None 434from strata_control import procs 435if isinstance (state ,dict )and procs .is_same (int (state .get ("pid" ,0 )),state .get ("token" )or "" ,state .get ("cmd" )): 436return state 437return 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.""" 442state = tunnel_info (name ) 443ok = False 444if state : 445from strata_control import procs 446outcome = procs .end_one ({"pid" :state ["pid" ],"token" :state ["token" ],"cmd" :state ["cmd" ]},grace = 5.0 ) 447ok = outcome in ("ended" ,"gone" ) 448try : 449_tunnel_state (name ).unlink () 450except OSError : 451pass 452return 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.""" 457low = line .lower () 458if any (w in low for w in ("token" ,"cert" ,"login" ,"secret" ,"authorize" ,"credential" )): 459return "" 460return line