okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
bcf88b738
main
1/** A supervised Cloudflare connector with a private, inference-only origin. */ 2import { spawn } from 'node:child_process' ; 3import { probe , which } from './util.mjs' ; 4import { classifyRunning , describeConnector , otherTunnelMessage , ownTunnelMessage } from './cloudflared-find.mjs' ; 5 6/** A tunnel without a key is allowed (owner decision, 0.2.2); because the link is public the warning is stronger than the local one. */ 7export const NO_KEY_TUNNEL_WARNING = 'No API key is set, so anyone who finds this link can use your model from the internet. Create an API key to protect it.' ; 8export function tunnelHostname ( value ) { 9const hostname = String ( value ?? '' ). trim (). toLowerCase (); 10if ( hostname . length > 253 || ! /^ (?:[ a - z0 - 9 ](?:[ a - z0 - 9- ]{ 0 , 61 }[ a - z0 - 9 ]) ? \. ) + [ a - z ]{ 2 , 63 } $ / . test ( hostname )) throw new Error ( 'Enter a hostname such as ai.example.com, without https:// or a path.' ); 11return hostname ; 12} 13export function createCloudflare ({ origin, originUrl, hasKey, changed= () => {}, launch= spawn , locate= async () => process . platform === 'win32' ?( await probe ( 'where.exe' , [ 'cloudflared' ])). split ( / \r ? \n / )[ 0 ] || null :which ( 'cloudflared' ), prepareConnector= null , connectorInfo= () => null , findRunning= async () => ({ running :false , kind :null , pids :[] }), timeoutMs= 45000 }) { 14let binary = null , other = null , child = null , timer = null , busy = false , generation = 0 ; 15let value = { status :'idle' , mode :null , url :null , error :null }; 16const state = () => { 17const info = binary ?connectorInfo () :null ; 18return { ...value , warning :value . status === 'connected' && ! hasKey () ?NO_KEY_TUNNEL_WARNING :null , installed :!! binary , originUrl, connector :info ?{ path :info . path , version :info . version , source :info . source , label :info . label , summary :describeConnector ( info ) } :null , external :other ?. running ?externalState () :null }; 19}; 20const update = patch => { value = { ...value , ...patch }; changed ( state ()); }; 21function externalState ( token = '' ) { 22const { own, others} = classifyRunning ( other , { originUrl, token}); 23return { kind :other . kind , others, own, message :own . length ?ownTunnelMessage ( own ) :otherTunnelMessage ( others ) }; 24} 25async function lookForOther () { try { other = await findRunning ({ exclude :[ child ?. pid ] }); } catch { other = null ; } return other ; } 26async function inspect () { binary = await locate (); await lookForOther (); changed ( state ()); return state (); } 27async function prepare () { 28if ( busy ) throw new Error ( 'Connector setup is already in progress.' ); 29busy = true ; 30try { 31binary = await locate (); 32if ( ! binary && prepareConnector ) binary = await prepareConnector (); 33if ( ! binary ) throw new Error ( 'The connector could not be prepared automatically.' ); 34update ({ error :null }); 35return state (); 36} finally { busy = false ; } 37} 38async function terminate () { 39clearTimeout ( timer ); timer = null ; 40const processRef = child ; child = null ; 41if ( processRef ) { 42await new Promise ( resolve => { 43const fallback = setTimeout (() => { processRef . kill ( 'SIGKILL' ); resolve (); }, 1500 ); 44processRef . once ( 'exit' , () => { clearTimeout ( fallback ); resolve (); }); 45processRef . kill ( 'SIGTERM' ); 46}); 47} 48await origin . stop (); 49} 50async function fail ( message , id ) { 51if ( id !== generation ) return ; 52++ generation ; busy = true ; update ({ status :'stopping' , error :message , url :null }); 53try { await terminate (); } finally { busy = false ; update ({ status :'error' }); } 54} 55async function start ( body ) { 56if ( busy || [ 'starting' , 'connected' , 'stopping' ]. includes ( value . status )) throw new Error ( 'Stop the current tunnel before starting another.' ); 57if ( ! [ 'quick' , 'domain' ]. includes ( body . mode )) throw new Error ( 'Choose a temporary URL or your own domain.' ); 58const hostname = body . mode === 'domain' ?tunnelHostname ( body . hostname ) :null ; 59const token = body . mode === 'domain' ?String ( body . token ?? '' ). trim () :'' ; 60if ( body . mode === 'domain' && ( ! /^ [ A - Za - z0 - 9+/=_- ]{ 20 , 8192 } $ / . test ( token ))) throw new Error ( 'Paste the tunnel token from Cloudflare, not the full installation command.' ); 61busy = true ; const id = ++ generation ; 62update ({ status :'starting' , mode :body . mode , url :null , error :null }); 63try { 64binary = await locate (); 65if ( ! binary && prepareConnector ) binary = await prepareConnector (); 66if ( ! binary ) throw new Error ( 'The connector could not be prepared automatically. Retry connector setup.' ); 67// Strata's own tunnel (same port or same token) is never doubled up. Other cloudflared processes serve other tunnels and are left alone. 68if (( await lookForOther ())?. running ) { const { own} = classifyRunning ( other , { originUrl, token}); if ( own . length ) throw new Error ( ownTunnelMessage ( own )); } 69await origin . start (); 70// Tokens never appear in command arguments, logs, saved settings, or API responses. 71const env = { ...process . env }; 72for ( const key of Object . keys ( env )) if ( key . startsWith ( 'TUNNEL_' )) delete env [ key ]; 73if ( token ) env . TUNNEL_TOKEN = token ; 74const args = [ 'tunnel' , '--no-autoupdate' , '--loglevel' , 'info' , '--grace-period' , '1s' , ...( hostname ?[ 'run' ] :[ '--url' , originUrl ])]; 75child = launch ( binary , args , { env, stdio :[ 'ignore' , 'pipe' , 'pipe' ], windowsHide :true }); 76let tail = '' , publicUrl = hostname ?`https:// ${ hostname } ` :null , registered = false ; 77const read = chunk => { 78if ( generation !== id ) return ; 79tail = ( tail + chunk . toString ()). slice ( - 16384 ); 80const match = tail . match ( / https:\/\/ [ a - z0 - 9- ] + \.trycloudflare\.com\b / ); 81if ( ! hostname && match ) publicUrl = match [ 0 ]; 82if ( / Registered tunnel connection / i . test ( tail )) registered = true ; 83if ( publicUrl && registered && value . status !== 'connected' ) { clearTimeout ( timer ); update ({ status :'connected' , url :` ${ publicUrl } /v1` }); } 84}; 85child . stdout ?. on ( 'data' , read ); child . stderr ?. on ( 'data' , read ); 86child . once ( 'error' , () => { void fail ( 'Cloudflared could not start. Check the installation and try again.' , id ); }); 87child . once ( 'exit' , () => { if ( generation === id ) { child = null ; void fail ( 'Cloudflared stopped. Check your network, token and Cloudflare configuration, then reconnect.' , id ); } }); 88timer = setTimeout (() => { void fail ( 'Cloudflare did not connect in time. Check your internet connection and tunnel setup, then try again.' , id ); }, timeoutMs ); 89timer . unref ?.(); 90return state (); 91} catch ( e ) { 92++ generation ; await terminate (); update ({ status :'error' , url :null , error :e . message }); throw e ; 93} finally { busy = false ; } 94} 95async function stop () { 96if ( busy ) throw new Error ( 'The tunnel is updating. Try again in a moment.' ); 97busy = true ; ++ generation ; update ({ status :'stopping' , url :null , error :null }); 98try { await terminate (); update ({ status :'idle' , mode :null }); return state (); } finally { busy = false ; } 99} 100return { state, inspect, prepare, start, stop}; 101}