okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
22a3d7068
main
1/** Shared helpers for the Strata host. */ 2import { createHash , randomUUID , timingSafeEqual } from 'node:crypto' ; 3import { execFile } from 'node:child_process' ; 4import { promisify } from 'node:util' ; 5import { whichCommand } from './platform-paths.mjs' ; 6 7export const exec = promisify ( execFile ); 8export const uid = ( prefix = 'id' ) => ` ${ prefix } _ ${ randomUUID (). slice ( 0 , 8 )} ` ; 9export const nowIso = () => new Date (). toISOString (); 10export const clamp = ( n , lo , hi ) => Math . min ( hi , Math . max ( lo , n )); 11export const round = ( n , d = 1 ) => Number ( n . toFixed ( d )); 12 13export function json ( res , status , body ) { 14const payload = JSON . stringify ( body ); 15res . writeHead ( status , { 16'content-type' :'application/json; charset=utf-8' , 17'content-length' :Buffer . byteLength ( payload ), 18'cache-control' :'no-store' , 19}); 20res . end ( payload ); 21} 22 23export function error ( res , status , message , extra = {}) { 24json ( res , status , { error :message , ...extra }); 25} 26 27/** 28* Two secrets compared in constant time (#4535). Both sides are hashed first, so the comparison always runs over two 29* 32-byte digests: neither the content nor the length of the given value can end it early. Anything that is not a 30* non-empty string never matches (an empty secret is "not set", not "equal to an empty header"). 31*/ 32export function sameSecret ( given , wanted ) { 33const ok = typeof given === 'string' && typeof wanted === 'string' && given . length > 0 && wanted . length > 0 ; 34const digest = value => createHash ( 'sha256' ). update ( typeof value === 'string' ?value :'' , 'utf8' ). digest (); 35return timingSafeEqual ( digest ( given ), digest ( wanted )) && ok ; 36} 37 38/** 39* The request's URL, or null when the request cannot be read as one (#4397). The Host header is the caller's: an empty 40* value, one with a space, a path, credentials or an unclosed bracket used to make `new URL` throw before the routing 41* try/catch and end the whole process. A missing Host (HTTP/1.0) is read as localhost; a good one keeps its port and IPv6 form. 42*/ 43export function requestUrl ( req ) { 44const host = req . headers ?. host ; 45try { 46let authority = 'localhost' ; 47if ( host !== undefined ) { 48if ( typeof host !== 'string' || ! host . trim () || / [ \s /?#@ \\ ] / . test ( host )) return null ; 49const base = new URL ( `http:// ${ host } ` ); 50if ( ! base . host || base . username || base . password || base . search || base . hash || base . pathname !== '/' ) return null ; 51authority = host ; 52} 53return new URL ( req . url ?? '/' , `http:// ${ authority } ` ); 54} catch { 55return null ; 56} 57} 58 59/** The answer to a request that could not be read as a URL: bounded, and the connection closes. */ 60export function badRequest ( res ) { 61if ( res . headersSent ) return res . end (); 62const payload = '{"error":"bad_host"}' ; 63res . writeHead ( 400 , { 'content-type' :'application/json; charset=utf-8' , 'content-length' :Buffer . byteLength ( payload ), 'cache-control' :'no-store' , connection :'close' }); 64res . end ( payload ); 65} 66 67export async function readBody ( req , limit = 4 * 1024 * 1024 ) { 68const chunks = []; 69let size = 0 ; 70for await ( const chunk of req ) { 71size += chunk . length ; 72if ( size > limit ) throw new Error ( 'Request body too large' ); 73chunks . push ( chunk ); 74} 75if ( ! chunks . length ) return {}; 76const raw = Buffer . concat ( chunks ). toString ( 'utf8' ); 77try { 78return JSON . parse ( raw ); 79} catch { 80throw new Error ( 'Body must be JSON' ); 81} 82} 83 84/** Run a command, returning stdout or '' when it is missing or fails. */ 85export async function probe ( cmd , args = [], timeout = 4000 ) { 86try { 87const { stdout} = await exec ( cmd , args , { timeout, maxBuffer :4 * 1024 * 1024 }); 88return stdout . trim (); 89} catch { 90return '' ; 91} 92} 93 94/** Where `binary` is on PATH, or null. `/usr/bin/env which` on POSIX, System32\where.exe on Windows (first match). */ 95export async function which ( binary , { env= process . env , platform= process . platform , run= probe } = {}) { 96const { command, args} = whichCommand ( binary , env , platform ); 97const out = await run ( command , args ); 98return out . split ( / \r ? \n / )[ 0 ]. trim () || null ; 99} 100 101/** Minimal SSE hub. */ 102export class EventHub { 103 #clients= new Set (); 104 105add ( res ) { 106res . writeHead ( 200 , { 107'content-type' :'text/event-stream; charset=utf-8' , 108'cache-control' :'no-cache, no-transform' , 109connection :'keep-alive' , 110'x-accel-buffering' :'no' , 111}); 112res . write ( ': connected\n\n' ); 113this . #clients. add ( res ); 114const ping = setInterval (() => res . write ( ': ping\n\n' ), 15000 ); 115res . on ( 'close' , () => { 116clearInterval ( ping ); 117this . #clients. delete ( res ); 118}); 119} 120 121send ( event , payload ) { 122const frame = `event: ${ event } \ndata: ${ JSON . stringify ( payload )} \n\n` ; 123for ( const res of this . #clients) { 124try { 125res . write ( frame ); 126} catch { 127this . #clients. delete ( res ); 128} 129} 130} 131 132get size () { 133return this . #clients. size ; 134} 135} 136 137/** The raw bytes of a request body (an upload), up to `limit`. */ 138export async function readRaw ( req , limit = 16 * 1024 * 1024 ) { 139const chunks = []; 140let size = 0 ; 141for await ( const chunk of req ) { 142size += chunk . length ; 143if ( size > limit ) throw new Error ( 'That upload is too big.' ); 144chunks . push ( chunk ); 145} 146return Buffer . concat ( chunks ); 147}