okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
3616148bb
main
1/** 2* Finding the Cloudflare connector (cloudflared) that is already on this computer. 3* 4* Strata used to look only in its own folders, so a cloudflared installed by the system (apt, brew, winget, a .deb) was 5* reported as "not installed" (Linux tester, cloudflared 2026.5.0 in /usr/bin). Now the places are, in this order: 6* 1. Strata's own connector folder 7* 2. the optional connector component folder 8* 3. every folder on PATH 9* 4. the usual install places (/usr/bin, /usr/local/bin, ~/.local/bin, Homebrew, Program Files, winget/choco/scoop) 10* The first one that runs `cloudflared --version` and is new enough is used; the answer says which one and from where. 11* Nothing here downloads or installs anything. 12*/ 13import { utf8Script } from './powershell-utf8.mjs' ; 14import { execFile } from 'node:child_process' ; 15import { access , stat } from 'node:fs/promises' ; 16import { constants } from 'node:fs' ; 17import { homedir } from 'node:os' ; 18import { win32 , posix } from 'node:path' ; 19 20/** The quick tunnel flags Strata passes (tunnel --url, --no-autoupdate, --grace-period) and the "Registered tunnel connection" log line it waits for exist from 2022.1.0. */ 21export const MIN_VERSION = '2022.1.0' ; 22 23export function parseVersion ( text ) { 24const m = / ( \d { 4 }) \. ( \d { 1 , 2 }) \. ( \d { 1 , 3 }) / . exec ( String ( text ?? '' )); 25return m ?[ Number ( m [ 1 ]), Number ( m [ 2 ]), Number ( m [ 3 ])] :null ; 26} 27export function versionAtLeast ( found , minimum = MIN_VERSION ) { 28const a = Array . isArray ( found ) ?found :parseVersion ( found ), b = Array . isArray ( minimum ) ?minimum :parseVersion ( minimum ); 29if ( ! a || ! b ) return true ; // an unreadable version (a custom build) is not a reason to refuse it 30for ( let i = 0 ; i < 3 ; i ++ ) if ( a [ i ] !== b [ i ]) return a [ i ] > b [ i ]; 31return true ; 32} 33 34const SOURCE_LABEL = { 35strata :'Strata’s own connector folder' , 36component :'the optional connector component' , 37path :'found on your PATH' , 38system :'a usual install location' , 39setting :'chosen with the STRATA_CLOUDFLARED setting' , 40}; 41 42/** Candidate paths in search order, each as { path, source }. Pure: no disk access. */ 43export function connectorCandidates ({ directory, componentDirectory= null , platform= process . platform , env= process . env , home= homedir (), search= true } = {}) { 44// STRATA_CLOUDFLARED=<file> uses exactly that connector; STRATA_CLOUDFLARED_SEARCH=own keeps the search to Strata's own folders. 45const windows = platform === 'win32' , p = windows ?win32 :posix ; 46const name = windows ?'cloudflared.exe' :'cloudflared' ; 47if ( env . STRATA_CLOUDFLARED ) return [{ path :env . STRATA_CLOUDFLARED , source :'setting' }]; 48if ( env . STRATA_CLOUDFLARED_SEARCH === 'own' ) search = false ; 49const out = [], seen = new Set (); 50const add = ( dir , source ) => { 51if ( ! dir ) return ; 52const path = p . join ( dir , name ), key = windows ?path . toLowerCase () :path ; 53if ( ! seen . has ( key )) { seen . add ( key ); out . push ({ path, source}); } 54}; 55add ( directory , 'strata' ); 56add ( componentDirectory , 'component' ); 57if ( ! search ) return out ; 58const pathVariable = windows ?( env . Path ?? env . PATH ?? '' ) :( env . PATH ?? '' ); 59for ( const dir of pathVariable . split ( windows ?';' :':' )) add ( dir . replace ( / ^" | "$ / g , '' ). trim (), 'path' ); 60if ( windows ) { 61const roots = [ env . ProgramFiles ?? 'C:\\Program Files' , env [ 'ProgramFiles(x86)' ] ?? 'C:\\Program Files (x86)' ]; 62for ( const root of roots ) add ( win32 . join ( root , 'cloudflared' ), 'system' ); 63if ( env . LOCALAPPDATA ) add ( win32 . join ( env . LOCALAPPDATA , 'Microsoft' , 'WinGet' , 'Links' ), 'system' ); 64add ( win32 . join ( env . ProgramData ?? 'C:\\ProgramData' , 'chocolatey' , 'bin' ), 'system' ); 65if ( home ) add ( win32 . join ( home , 'scoop' , 'shims' ), 'system' ); 66} else { 67for ( const dir of [ '/usr/bin' , '/usr/local/bin' , '/opt/homebrew/bin' , '/home/linuxbrew/.linuxbrew/bin' , '/snap/bin' , '/opt/cloudflared' ]) add ( dir , 'system' ); 68if ( home ) { add ( posix . join ( home , '.local' , 'bin' ), 'system' ); add ( posix . join ( home , 'bin' ), 'system' ); add ( posix . join ( home , '.cloudflared' ), 'system' ); } 69} 70return out ; 71} 72 73/** Runs `<path> --version`; resolves to the combined output, rejects when it does not run. */ 74export function runVersion ( path ) { 75return new Promise (( resolve , reject ) => { 76execFile ( path , [ '--version' ], { timeout :10000 , windowsHide :true , maxBuffer :1024 * 1024 }, ( error , stdout , stderr ) => { 77if ( error ) reject ( error ); else resolve ( ` ${ stdout } \n ${ stderr } ` . trim ()); 78}); 79}); 80} 81 82async function isRunnableFile ( path , platform ) { 83try { 84if ( ! ( await stat ( path )). isFile ()) return false ; 85await access ( path , platform === 'win32' ?constants . F_OK :constants . X_OK ); 86return true ; 87} catch { return false ; } 88} 89 90/** 91* The connector to use, and what was seen on the way. 92* Resolves to { found: { path, version, source, label } | null, skipped: [{ path, source, reason, version? }] }. 93* `tooOld` is set when something was found but every copy is older than the minimum version. 94*/ 95export async function findConnector ( options = {}) { 96const platform = options . platform ?? process . platform ; 97const run = options . run ?? runVersion ; 98const usable = options . usable ?? ( path => isRunnableFile ( path , platform )); 99const skipped = []; 100for ( const candidate of connectorCandidates ( options )) { 101if ( ! ( await usable ( candidate . path ))) continue ; 102let output ; 103try { output = await run ( candidate . path ); } 104catch { skipped . push ({ ...candidate , reason :'does-not-run' }); continue ; } 105if ( ! /cloudflared / i . test ( output ) && ! parseVersion ( output )) { skipped . push ({ ...candidate , reason :'not-cloudflared' }); continue ; } 106const parsed = parseVersion ( output ), version = parsed ?parsed . join ( '.' ) :null ; 107if ( ! versionAtLeast ( parsed )) { skipped . push ({ ...candidate , reason :'too-old' , version}); continue ; } 108return { found :{ path :candidate . path , version, source :candidate . source , label :SOURCE_LABEL [ candidate . source ] }, skipped}; 109} 110return { found :null , skipped}; 111} 112 113/** A person-readable sentence about what was found (shown in the Connector step and the review). */ 114export function describeConnector ( found ) { 115if ( ! found ) return null ; 116return ` ${ found . version ? `cloudflared ${ found . version } ` : 'cloudflared' } · ${ found . path } ( ${ found . label } )` ; 117} 118 119/** A person-readable reason when nothing usable was found but something unusable was. Null when nothing was seen. */ 120export function skippedMessage ( skipped ) { 121const old = skipped . find ( s => s . reason === 'too-old' ); 122if ( old ) return `The cloudflared at ${ old . path } is version ${ old . version } , which is too old. Strata needs ${ MIN_VERSION } or newer. Update cloudflared, then retry.` ; 123const broken = skipped . find ( s => s . reason === 'does-not-run' || s . reason === 'not-cloudflared' ); 124if ( broken ) return `The file at ${ broken . path } did not run as cloudflared. Reinstall cloudflared, then retry.` ; 125return null ; 126} 127 128/** 129* Which cloudflared processes run on this computer (a system service, one the person started, another program's tunnel)? 130* `exclude` is the list of pids that belong to Strata itself. Resolves to { running, kind: 'service' | 'process' | null, pids, procs } 131* where procs is [{ pid, command }] (the command line is for matching only: it can hold a tunnel token and is never shown). 132* Failing to look is "not running": a missing ps must never block the tunnel. 133*/ 134export async function findRunningConnector ({ platform= process . platform , exclude= [], run= defaultProbe } = {}) { 135const skip = new Set ( exclude . filter ( Number . isInteger )); 136let procs = []; 137if ( platform === 'win32' ) { 138const out = await run ( 'powershell.exe' , [ '-NoProfile' , '-NonInteractive' , '-Command' , utf8Script ( "Get-CimInstance Win32_Process -Filter \"Name='cloudflared.exe'\" | ForEach-Object { \"$($_.ProcessId)`t$($_.CommandLine)\" }" )]); 139procs = out . split ( / \r ? \n / ). map ( l => / ^ ( \d + ) \t ( . * ) $ / . exec ( l )). filter ( Boolean ). map ( m => ({ pid :Number ( m [ 1 ]), command :m [ 2 ] })); 140if ( ! procs . length ) { // no PowerShell answer: at least the pids 141const list = await run ( 'tasklist' , [ '/FI' , 'IMAGENAME eq cloudflared.exe' , '/NH' , '/FO' , 'CSV' ]); 142procs = [ ...list . matchAll ( / "cloudflared\.exe"," ( \d + ) " / gi )]. map ( m => ({ pid :Number ( m [ 1 ]), command :'' })); 143} 144} else { 145const out = await run ( 'ps' , [ '-axo' , 'pid=,comm=,args=' ]); 146procs = out . split ( '\n' ). map ( l => / ^\s * ( \d + ) \s + ( \S + ) \s * ( . * ) $ / . exec ( l )). filter ( m => m && / ( ^ | \/ ) cloudflared$ / . test ( m [ 2 ])). map ( m => ({ pid :Number ( m [ 1 ]), command :m [ 3 ] })); 147} 148procs = procs . filter ( p => ! skip . has ( p . pid )); 149if ( ! procs . length ) return { running :false , kind :null , pids :[], procs :[] }; 150let kind = 'process' ; 151if ( platform === 'linux' ) { 152const active = ( await run ( 'systemctl' , [ 'is-active' , 'cloudflared' ])). trim (); 153if ( active === 'active' ) kind = 'service' ; 154} else if ( platform === 'win32' ) { 155const service = await run ( 'sc.exe' , [ 'query' , 'Cloudflared' ]); 156if ( / RUNNING / . test ( service )) kind = 'service' ; 157} 158return { running :true , kind, pids :procs . map ( p => p . pid ), procs}; 159} 160 161/** 162* Split the running connectors into Strata's own tunnel (same port: its command line has --url pointing at `originUrl`'s port; same tunnel: 163* its command line holds the same token) and tunnels of something else, which are none of Strata's business. 164*/ 165export function classifyRunning ( running , { originUrl= '' , token= '' } = {}) { 166const port = / : ( \d + ) \/ ? $ / . exec ( String ( originUrl ))?.[ 1 ] ?? null ; 167const own = [], others = []; 168for ( const p of running ?. procs ?? []) { 169const cmd = p . command ?? '' ; 170const samePort = !! port && new RegExp ( `--url[= ]\\S*: ${ port } (?:/|\\s|$)` ). test ( cmd ); 171const sameToken = token . length >= 20 && cmd . includes ( token ); 172( samePort || sameToken ?own :others ). push ( p . pid ); 173} 174return { own, others}; 175} 176 177const pidList = pids => pids . join ( ', ' ); 178/** Plain sentence about tunnels that are none of Strata's business (information only, never a refusal). */ 179export function otherTunnelMessage ( pids ) { 180if ( ! pids ?. length ) return null ; 181return pids . length === 1 ?`cloudflared is already running for another tunnel (PID ${ pids [ 0 ]} ).` :`cloudflared is already running for other tunnels (PIDs ${ pidList ( pids )} ).` ; 182} 183/** The refusal for Strata's own tunnel already running. */ 184export function ownTunnelMessage ( pids ) { 185if ( ! pids ?. length ) return null ; 186return `Strata’s tunnel for this address is already running (PID ${ pidList ( pids )} ), so Strata did not start a second one. Stop it first (or use it as it is), then connect again here.` ; 187} 188 189function defaultProbe ( cmd , args ) { 190return new Promise ( resolve => { 191execFile ( cmd , args , { timeout :4000 , windowsHide :true , maxBuffer :1024 * 1024 }, ( error , stdout ) => resolve ( error ?'' :String ( stdout ))); 192}); 193}