okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
8667a3dbf
main
1/** 2* Files dropped on the app window (Linux and macOS). 3* 4* The page cannot read a dragged file there: WebKit gives it the drag events but no files. The app shell sees the drop with the real paths and 5* hands them to the host with its shell secret (POST /api/app/drop); the host reads the files and keeps them for a short time under 6* unguessable ids; the page asks for each id once (GET /api/app/drop/<id>) and attaches the files as if they had been dropped in a browser. 7* Only regular files up to MAX_BYTES, at most MAX_FILES per drop; folders and anything else are skipped. 8*/ 9import { randomUUID } from 'node:crypto' ; 10import { readFile , stat } from 'node:fs/promises' ; 11import { basename , extname , isAbsolute } from 'node:path' ; 12 13export const MAX_FILES = 10 , MAX_BYTES = 25 * 1024 * 1024 , KEEP_MS = 2 * 60_000 ; 14 15const TYPES = { 16png :'image/png' , jpg :'image/jpeg' , jpeg :'image/jpeg' , gif :'image/gif' , webp :'image/webp' , bmp :'image/bmp' , 17txt :'text/plain' , md :'text/markdown' , markdown :'text/markdown' , csv :'text/csv' , json :'application/json' , log :'text/plain' , 18html :'text/html' , htm :'text/html' , xml :'text/xml' , yaml :'text/yaml' , yml :'text/yaml' , 'application/pdf' , 19}; 20export const typeOfName = name => TYPES [ extname ( String ( name )). slice ( 1 ). toLowerCase ()] ?? 'application/octet-stream' ; 21 22export function createNativeDrops ({ now= Date . now , read= readFile , info= stat } = {}) { 23const held = new Map (); // id -> { name, type, bytes, at } 24const sweep = () => { for ( const [ id , f ] of held ) if ( now () - f . at > KEEP_MS ) held . delete ( id ); }; 25return { 26/** Read the dropped paths; answer what the page may ask for: [{ id, name, type, size }]. */ 27async add ( paths ) { 28sweep (); 29const out = []; 30for ( const raw of ( Array . isArray ( paths ) ?paths :[]). slice ( 0 , MAX_FILES )) { 31const path = typeof raw === 'string' ?raw :'' ; 32if ( ! path || path . includes ( '\0' ) || ! isAbsolute ( path )) continue ; 33try { 34const st = await info ( path ); 35if ( ! st . isFile () || st . size > MAX_BYTES ) continue ; 36const bytes = await read ( path ); 37const id = randomUUID (); 38const name = basename ( path ); 39held . set ( id , { name, type :typeOfName ( name ), bytes, at :now () }); 40out . push ({ id, name, type :typeOfName ( name ), size :bytes . length }); 41} catch { /* an unreadable file is skipped, the rest still arrive */ } 42} 43return out ; 44}, 45/** One use per id. */ 46take ( id ) { sweep (); const f = held . get ( id ); if ( f ) held . delete ( id ); return f ?? null ; }, 47}; 48}