okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
788e0b731
main
1/** 2* Files and pictures dropped or pasted into a chat. 3* 4* `POST /api/chat/upload?sessionId=&name=` takes the bytes in any of three forms: multipart/form-data (one or more files), a JSON body 5* { name, dataUrl } (a pasted or read picture), or the raw bytes with the file's type. A picture is kept as an upload the next message 6* can name (imageIds) and is shown again by its id; any other file is saved inside the chat's folder under .strata/attachments and named 7* in the next message (@path), so the assistant reads it. Nothing is ever written outside those two places. 8*/ 9 10import { randomUUID } from 'node:crypto' ; 11import { existsSync , mkdirSync , readFileSync , readdirSync , statSync , unlinkSync , writeFileSync } from 'node:fs' ; 12import { basename , extname , join } from 'node:path' ; 13 14export const IMAGE_TYPES = { 'image/png' :'png' , 'image/jpeg' :'jpg' , 'image/webp' :'webp' }; 15export const MAX_UPLOAD_BYTES = 12 * 1024 * 1024 ; 16export const MAX_IMAGE_BYTES = 6 * 1024 * 1024 ; 17export const MAX_IMAGES = 4 ; 18 19const safeName = name => String ( name ?? 'file' ). replace ( / [ \\ /:*?"<>| \x00 - \x1f ] / g , '_' ). replace ( / ^\. +/ , '' ). slice ( 0 , 120 ) || 'file' ; 20 21/** The files of a multipart/form-data body: [{ name, type, bytes }]. */ 22export function parseMultipart ( body , contentType ) { 23const m = / boundary= (?: " ([ ^ " ] + ) " | ([ ^ ; ] + )) / i . exec ( String ( contentType ?? '' )); 24if ( ! m ) throw new Error ( 'This upload is not readable. Try again.' ); 25const boundary = Buffer . from ( '--' + ( m [ 1 ] ?? m [ 2 ]). trim ()); 26const files = []; 27let at = body . indexOf ( boundary ); 28while ( at >= 0 ) { 29const next = body . indexOf ( boundary , at + boundary . length ); 30if ( next < 0 ) break ; 31let part = body . subarray ( at + boundary . length , next ); 32if ( part . subarray ( 0 , 2 ). toString () === '\r\n' ) part = part . subarray ( 2 ); 33const head = part . indexOf ( '\r\n\r\n' ); 34if ( head > 0 ) { 35const headers = part . subarray ( 0 , head ). toString ( 'utf8' ); 36let data = part . subarray ( head + 4 ); 37if ( data . subarray ( - 2 ). toString () === '\r\n' ) data = data . subarray ( 0 , - 2 ); 38const file = / filename=" ([ ^ " ] * ) " / i . exec ( headers ); 39if ( file ) files . push ({ name :file [ 1 ] || 'file' , type :( / content-type:\s * ([ ^ \r\n ; ] + ) / i . exec ( headers )?.[ 1 ] ?? 'application/octet-stream' ). trim (). toLowerCase (), bytes :Buffer . from ( data ) }); 40} 41at = next ; 42} 43if ( ! files . length ) throw new Error ( 'No file was in this upload.' ); 44return files ; 45} 46 47const typeFromBytes = b => ( b . subarray ( 0 , 8 ). equals ( Buffer . from ([ 137 , 80 , 78 , 71 , 13 , 10 , 26 , 10 ])) ?'image/png' :b . subarray ( 0 , 3 ). equals ( Buffer . from ([ 255 , 216 , 255 ])) ?'image/jpeg' :b . subarray ( 0 , 4 ). toString () === 'RIFF' && b . subarray ( 8 , 12 ). toString () === 'WEBP' ?'image/webp' :null ); 48 49export function createUploads ({ dir, folderOf, attachments}) { 50mkdirSync ( dir , { recursive :true }); 51const index = new Map (); // id -> { id, chatId, name, type, size, file } 52const metaFile = id => join ( dir , id + '.json' ); 53const load = id => { 54if ( index . has ( id )) return index . get ( id ); 55try { const m = JSON . parse ( readFileSync ( metaFile ( id ), 'utf8' )); index . set ( id , m ); return m ; } catch { return null ; } 56}; 57 58/** Store one file; returns what the page needs to show it. */ 59function saveOne ( chatId , f ) { 60if ( f . bytes . length > MAX_UPLOAD_BYTES ) throw Object . assign ( new Error ( `" ${ safeName ( f . name )} " is bigger than ${ MAX_UPLOAD_BYTES / 1024 / 1024 } MB.` ), { code :'too-big' }); 61// A picture is recognised by its first bytes, not by the name or the type the sender claimed. 62const real = typeFromBytes ( f . bytes ); 63if ( real ) { 64if ( f . bytes . length > MAX_IMAGE_BYTES ) throw Object . assign ( new Error ( `The picture " ${ safeName ( f . name )} " is bigger than ${ MAX_IMAGE_BYTES / 1024 / 1024 } MB. Choose a smaller one.` ), { code :'too-big' }); 65const id = randomUUID (); 66const file = join ( dir , id + '.' + IMAGE_TYPES [ real ]); 67writeFileSync ( file , f . bytes ); 68const meta = { id, chatId, name :safeName ( f . name ), type :real , size :f . bytes . length , file, kind :'image' }; 69writeFileSync ( metaFile ( id ), JSON . stringify ( meta )); index . set ( id , meta ); 70return { id, kind :'image' , name :meta . name , type :real , size :meta . size , url :`/api/chat/upload/ ${ id } ` }; 71} 72if ( / ^image\/ / i . test ( f . type )) throw Object . assign ( new Error ( `" ${ safeName ( f . name )} " is a picture type the model cannot read. Use PNG, JPEG or WebP.` ), { code :'bad-image' }); 73const root = folderOf ( chatId ); 74const target = join ( root , '.strata' , 'attachments' ); 75mkdirSync ( target , { recursive :true }); 76let name = safeName ( f . name ), n = 1 ; 77while ( existsSync ( join ( target , name ))) name = ` ${ basename ( f . name , extname ( f . name ))} - ${ ++ n } ${ extname ( f . name )} ` . replace ( / [ \\ /:*?"<>| ] / g , '_' ); 78const path = join ( target , name ); 79writeFileSync ( path , f . bytes ); 80attachments . add ( chatId , path ); 81return { id :null , kind :'file' , name, type :f . type , size :f . bytes . length , path, attached :true }; 82} 83 84return { 85/** Accept a request body in any of the three forms. */ 86accept ( chatId , { body, contentType, name}) { 87const ct = String ( contentType ?? '' ); 88let files ; 89if ( / ^multipart\/form-data / i . test ( ct )) files = parseMultipart ( body , ct ); 90else if ( / ^application\/json / i . test ( ct )) { 91const j = JSON . parse ( body . toString ( 'utf8' ) || '{}' ); 92const list = Array . isArray ( j . files ) ?j . files :[ j ]; 93files = list . map ( x => { 94const m = / ^data: ([ ^ ;, ] + ) ;base64, ([ A - Za - z0 - 9+/= ] + ) $ / . exec ( String ( x . dataUrl ?? x . url ?? '' )); 95if ( ! m ) throw new Error ( 'A picture must be sent as a data address (data:image/png;base64,...).' ); 96return { name :x . name ?? 'Picture' , type :m [ 1 ], bytes :Buffer . from ( m [ 2 ], 'base64' ) }; 97}); 98} else files = [{ name :name ?? 'file' , type :ct || 'application/octet-stream' , bytes :body }]; 99if ( files . length > 10 ) throw new Error ( 'Drop up to ten files at a time.' ); 100return files . map ( f => saveOne ( chatId , f )); 101}, 102/** The picture of an upload as { bytes, type, name }, for the page and for the model. */ 103image ( id ) { 104const m = load ( String ( id )); 105if ( ! m || m . kind !== 'image' ) return null ; 106try { return { bytes :readFileSync ( m . file ), type :m . type , name :m . name , chatId :m . chatId }; } catch { return null ; } 107}, 108/** The pictures a message names (imageIds), as data addresses the engine and the agent take. */ 109dataUrls ( chatId , ids ) { 110const list = Array . isArray ( ids ) ?ids :[]; 111if ( list . length > MAX_IMAGES ) throw new Error ( `Attach up to ${ MAX_IMAGES } pictures per message.` ); 112return list . map ( id => { 113const img = this . image ( id ); 114if ( ! img || ( img . chatId && chatId && img . chatId !== chatId )) throw new Error ( 'A picture is no longer available. Attach it again.' ); 115return { url :`data: ${ img . type } ;base64, ${ img . bytes . toString ( 'base64' )} ` , name :img . name }; 116}); 117}, 118/** Remove uploads older than a day (the folder never grows without end). */ 119sweep ( maxAgeMs = 24 * 3600_000 ) { 120let removed = 0 ; 121for ( const f of readdirSync ( dir )) { const p = join ( dir , f ); try { if ( Date . now () - statSync ( p ). mtimeMs > maxAgeMs ) { unlinkSync ( p ); removed += 1 ; } } catch { /* gone already */ } } 122return removed ; 123}, 124}; 125}