okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
03d709820
main
1import test from 'node:test' ; 2import assert from 'node:assert/strict' ; 3import { spawn } from 'node:child_process' ; 4import { mkdtemp , rm } from 'node:fs/promises' ; 5import { tmpdir } from 'node:os' ; 6import { join } from 'node:path' ; 7import { createServer } from 'node:net' ; 8import { fileURLToPath } from 'node:url' ; 9import { EventEmitter } from 'node:events' ; 10import { createAppUi , openInBrowser , startOpener , APP_UPDATE_UNAVAILABLE , BROWSER_UPDATE_MESSAGE } from '../server/app-ui.mjs' ; 11import { checkComponentUpdates } from '../server/updates.mjs' ; 12 13const root = fileURLToPath ( new URL ( '..' , import . meta. url )); 14const delay = ms => new Promise ( r => setTimeout ( r , ms )); 15/** Wait until `done()` is true, polling every 10 ms for up to `ms` (a busy PC can hold a timer back by far more than a fixed 20 ms sleep). */ 16const until = async ( done , ms = 5000 ) => { const end = Date . now () + ms ; while ( ! done () && Date . now () < end ) await delay ( 10 ); return done (); }; 17const bridgeEnv = { STRATA_SHELL_BRIDGE :'http://127.0.0.1:5555' , STRATA_SHELL_TOKEN :'a' . repeat ( 32 ) }; 18 19test ( 'a host nobody started has no window mode, no Quit and no updater' , () => { 20const ui = createAppUi ({ env :{} }); 21assert . deepEqual ( ui . state (), { mode :null , reason :null , canQuit :false , appUpdate :'unavailable' }); 22assert . equal ( ui . updater , null ); 23assert . equal ( ui . quit (). ok , false ); 24}); 25 26test ( 'window mode: no Quit entry (closing the window ends everything), the updater waits for the window process' , async () => { 27const ui = createAppUi ({ env :{ STRATA_UI_MODE :'window' } }); 28assert . equal ( ui . state (). canQuit , false ); 29assert . equal ( ui . state (). appUpdate , 'available' ); 30assert . equal ( ui . quit (). status , 409 ); 31await assert . rejects ( ui . updater . check (), error => error . code === APP_UPDATE_UNAVAILABLE ); 32ui . setBridge ({ url :'http://127.0.0.1:6001' , token :'b' . repeat ( 32 ) }); 33assert . ok ( ui . updater ); 34assert . throws (() => ui . setBridge ({ url :'http://example.com:1' , token :'b' . repeat ( 32 ) }), / not a bridge / ); 35assert . throws (() => ui . setBridge ({ url :'http://127.0.0.1:6001' , token :'short' }), / not a bridge / ); 36}); 37 38test ( 'browser mode (chosen): Quit works once and the app updater says why it is not available' , async () => { 39let stopped = 0 ; 40const ui = createAppUi ({ env :{ STRATA_UI_MODE :'browser' }, shutdown :() => { stopped ++ ; } }); 41assert . deepEqual ( ui . state (), { mode :'browser' , reason :'chosen' , canQuit :true , appUpdate :'unavailable' }); 42assert . equal ( ui . updater . unavailable , BROWSER_UPDATE_MESSAGE ); 43await assert . rejects ( ui . updater . check (), error => error . code === APP_UPDATE_UNAVAILABLE && error . message === BROWSER_UPDATE_MESSAGE ); 44assert . equal ( ui . quit (). status , 202 ); 45assert . ok ( await until (() => stopped >= 1 ), 'the shutdown callback ran' ); 46await delay ( 50 ); // and only once 47assert . equal ( stopped , 1 ); 48}); 49 50test ( 'the shell moves a window host to a browser tab: opens the page, sends the notice, drops the window updater' , async () => { 51const opened = [], notices = []; 52const ui = createAppUi ({ env :{ STRATA_UI_MODE :'window' }, open :async url => { opened . push ( url ); return true ; }, notify :async text => { notices . push ( text ); } }); 53ui . setBridge ({ url :'http://127.0.0.1:6001' , token :'b' . repeat ( 32 ) }); 54const out = await ui . switchToBrowser ({ url :'http://127.0.0.1:47831/' , notice :'Strata opened in your browser because the app window couldn\'t start on this computer.' }); 55assert . deepEqual ( out , { mode :'browser' , reason :'window-failed' , opened :true }); 56assert . deepEqual ( opened , [ 'http://127.0.0.1:47831/' ]); 57assert . equal ( notices . length , 1 ); 58assert . equal ( ui . state (). canQuit , true ); 59await assert . rejects ( ui . updater . check (), error => error . code === APP_UPDATE_UNAVAILABLE ); 60// no browser could be opened: the shell is told, it prints the address 61const none = createAppUi ({ env :{ STRATA_UI_MODE :'window' }, open :async () => false , notify :async () => false }); 62assert . equal (( await none . switchToBrowser ({ url :'http://127.0.0.1:1/' })). opened , false ); 63}); 64 65test ( 'openers are tried in order until one takes the address' , async () => { 66const tried = []; 67const ok = await openInBrowser ( 'http://127.0.0.1:1/' , { openers :[[ 'xdg-open' ], [ 'gio' , 'open' ], [ 'firefox' ]], start :async ( cmd , args ) => { tried . push ([ cmd , ...args ]. join ( ' ' )); return cmd === 'gio' ; } }); 68assert . equal ( ok , true ); 69assert . deepEqual ( tried , [ 'xdg-open http://127.0.0.1:1/' , 'gio open http://127.0.0.1:1/' ]); 70assert . equal ( await openInBrowser ( 'x' , { openers :[[ 'a' ], [ 'b' ]], start :async () => false }), false ); 71}); 72 73test ( 'an opener that is missing or fails fast is a failure; one still running is a success' , async () => { 74const fake = behaviour => () => { const child = new EventEmitter (); child . unref = () => {}; queueMicrotask (() => behaviour ( child )); return child ; }; 75assert . equal ( await startOpener ( 'x' , [], { env :{}, settleMs :200 , spawnProcess :fake ( c => c . emit ( 'error' , new Error ( 'ENOENT' ))) }), false ); 76assert . equal ( await startOpener ( 'x' , [], { env :{}, settleMs :200 , spawnProcess :fake ( c => c . emit ( 'exit' , 3 )) }), false ); 77assert . equal ( await startOpener ( 'x' , [], { env :{}, settleMs :200 , spawnProcess :fake ( c => c . emit ( 'exit' , 0 )) }), true ); 78assert . equal ( await startOpener ( 'x' , [], { env :{}, settleMs :50 , spawnProcess :fake (() => {}) }), true ); 79}); 80 81test ( 'update check in browser mode: the app part says it cannot be done here, engine/component updates stay possible' , async () => { 82const control = { version :'0.1.0' , updateCheck :async () => ({ app :{ status :'available' , offered :'0.2.0' , notes :'Faster.' }, engine :{ status :'current' , installed :{ version :'1' } }, control :{ status :'current' } }) }; 83const browser = createAppUi ({ env :{ STRATA_UI_MODE :'browser' } }); 84const inBrowser = await checkComponentUpdates ({ control, appUpdater :browser . updater , appVersion :'0.1.0' }); 85assert . equal ( inBrowser . strata . status , 'available' ); 86assert . equal ( inBrowser . strata . canInstall , false ); 87assert . match ( inBrowser . strata . message , / can't be updated in browser mode / ); 88// the same check with the window's updater in place offers the update as before 89const windowed = createAppUi ({ env :{ STRATA_UI_MODE :'window' , ...bridgeEnv }, createUpdater :({ env}) => env . STRATA_SHELL_BRIDGE ?{ check :async () => ({ available :true , version :'0.2.0' , notes :'Faster.' }), install :async () => {} } :null }); 90const inWindow = await checkComponentUpdates ({ control, appUpdater :windowed . updater , appVersion :'0.1.0' }); 91assert . equal ( inWindow . strata . canInstall , true ); 92assert . doesNotMatch ( inWindow . strata . message , / browser mode / ); 93}); 94 95async function freePort () { const s = createServer (); await new Promise ( r => s . listen ( 0 , '127.0.0.1' , r )); const p = s . address (). port ; await new Promise ( r => s . close ( r )); return p ; } 96 97async function startHost ( extraEnv ) { 98const home = await mkdtemp ( join ( tmpdir (), 'strata-host-appui-' )); 99const port = await freePort (); 100const host = spawn ( process . execPath , [ 'server/index.mjs' ], { 101cwd :root , stdio :'ignore' , 102env :{ ...process . env , STRATA_HOME :home , STRATA_MODELS_DIR :join ( home , 'models' ), STRATA_PORT :String ( port ), STRATA_SHARE_PORT :String ( await freePort ()), STRATA_TUNNEL_PORT :String ( await freePort ()), STRATA_NO_ACQUIRE :'1' , STRATA_NO_BUNDLED_ENGINE :'1' , ...extraEnv }, 103}); 104let up = false ; 105for ( let i = 0 ; i < 150 && ! up ; i ++ ) { try { up = ( await fetch ( `http://127.0.0.1: ${ port } /api/health` )). ok ; } catch { await delay ( 100 ); } } 106assert . ok ( up , 'the host answers' ); 107const exited = new Promise ( resolve => host . on ( 'exit' , code => resolve ( code ))); 108return { port, host, exited, home, base :`http://127.0.0.1: ${ port } ` }; 109} 110 111test ( 'browser-mode host over HTTP: mode, Quit needs the client header, then the host stops cleanly and only listens on 127.0.0.1' , async () => { 112const { port, host, exited, home, base} = await startHost ({ STRATA_UI_MODE :'browser' }); 113try { 114const mode = await ( await fetch ( ` ${ base } /api/app/mode` )). json (); 115assert . equal ( mode . mode , 'browser' ); assert . equal ( mode . canQuit , true ); 116// a plain POST (what a web page could send without asking first) is refused, and so is a page from another site 117assert . equal (( await fetch ( ` ${ base } /api/app/quit` , { method :'POST' })). status , 403 ); 118assert . equal (( await fetch ( ` ${ base } /api/app/quit` , { method :'POST' , headers :{ 'x-strata-client' :'ui' , origin :'https://example.com' } })). status , 403 ); 119// the shell's own routes need the secret 120assert . equal (( await fetch ( ` ${ base } /api/control/ui` , { method :'POST' , body :'{}' })). status , 403 ); 121// it is listening on the loopback address only 122const { networkInterfaces} = await import ( 'node:os' ); 123const other = Object . values ( networkInterfaces ()). flat (). find ( i => i && ! i . internal && i . family === 'IPv4' ); 124if ( other ) await assert . rejects ( fetch ( `http:// ${ other . address } : ${ port } /api/health` , { signal :AbortSignal . timeout ( 2000 ) })); 125assert . equal (( await fetch ( ` ${ base } /api/app/quit` , { method :'POST' , headers :{ 'x-strata-client' :'ui' } })). status , 202 ); 126assert . equal ( await Promise . race ([ exited , delay ( 30000 ). then (() => 'still running' )]), 0 ); 127} finally { host . kill (); await rm ( home , { recursive :true , force :true }); } 128}); 129 130test ( 'window-mode host over HTTP: Quit is refused; the shell (with its secret) registers the bridge and can move the host to browser mode' , async () => { 131const secret = 'c' . repeat ( 64 ); 132const { host, home, base} = await startHost ({ STRATA_UI_MODE :'window' , STRATA_SHUTDOWN_TOKEN :secret , STRATA_OPENER :'record' }); 133try { 134assert . equal (( await fetch ( ` ${ base } /api/app/quit` , { method :'POST' , headers :{ 'x-strata-client' :'ui' } })). status , 409 ); 135const as = ( body , token = secret ) => fetch ( ` ${ base } /api/control/ui` , { method :'POST' , headers :{ 'x-strata-shutdown' :token , 'content-type' :'application/json' }, body :JSON . stringify ( body ) }); 136assert . equal (( await as ({}, 'd' . repeat ( 64 ))). status , 403 ); 137assert . equal (( await as ({ bridge :{ url :'http://evil.example:1' , token :'e' . repeat ( 32 ) } })). status , 400 ); 138assert . equal (( await as ({ bridge :{ url :'http://127.0.0.1:9' , token :'e' . repeat ( 32 ) } })). status , 200 ); 139const moved = await ( await as ({ mode :'browser' , reason :'window-failed' , open :false })). json (); 140assert . equal ( moved . mode , 'browser' ); 141assert . equal (( await ( await fetch ( ` ${ base } /api/app/mode` )). json ()). reason , 'window-failed' ); 142} finally { host . kill (); await rm ( home , { recursive :true , force :true }); } 143});