'use strict'; const U=require('./util.cjs'); const C=require('./catalog.cjs'); const INPUT_KEYS=['expectedVersion','favorites','savedSearches']; const RECORD_KEYS=['version','favorites','savedSearches','updatedAt','simulation']; const SEARCH_KEYS=['id','name','query','country','category','benefit','sort','favoritesOnly']; const COUNTRIES=['','AE','SG','US','HK','GB']; const CATEGORIES=['','Real estate','Private credit','Treasury','Commodities']; const BENEFITS=['','discount','time','volume','points']; const SORTS=['featured','minTicketAsc','minTicketDesc','closing']; const SEARCH_ID=/^[A-Za-z0-9_-]{12,90}$/; const SHA256=/^[a-f0-9]{64}$/; const OFFER_IDS=new Set(C.catalog().offers.map(offer=>offer.id)); const instant=value=>typeof value==='string'&&Number.isFinite(Date.parse(value))&&new Date(value).toISOString()===value; const digest=row=>U.hash(U.canonical({userId:row.user_id,data:row.data})); const exact=(value,keys)=>{ U.object(value,keys); if(Object.keys(value).length!==keys.length)U.fail('invalid'); return value; }; function parseLists(input){ if(!Array.isArray(input.favorites)||input.favorites.length>32||new Set(input.favorites).size!==input.favorites.length||input.favorites.some(id=>typeof id!=='string'||!OFFER_IDS.has(id)))U.fail('invalid'); if(!Array.isArray(input.savedSearches)||input.savedSearches.length>10)U.fail('invalid'); const ids=new Set(); const savedSearches=input.savedSearches.map(value=>{ const search=exact(value,SEARCH_KEYS); if(typeof search.id!=='string'||!SEARCH_ID.test(search.id)||ids.has(search.id)||typeof search.name!=='string'||typeof search.query!=='string'||!COUNTRIES.includes(search.country)||!CATEGORIES.includes(search.category)||!BENEFITS.includes(search.benefit)||!SORTS.includes(search.sort)||typeof search.favoritesOnly!=='boolean')U.fail('invalid'); const name=search.name.trim(),query=search.query.trim(); if(!name||name.length>60||query.length>200)U.fail('invalid'); ids.add(search.id); return {id:search.id,name,query,country:search.country,category:search.category,benefit:search.benefit,sort:search.sort,favoritesOnly:search.favoritesOnly}; }); return {favorites:input.favorites.slice(),savedSearches}; } function verifyStoredDiscoveryTool(row){ try{ if(!row||typeof row.user_id!=='string'||!row.user_id||row.user_id.length>100||typeof row.data!=='string'||typeof row.data_hash!=='string'||!SHA256.test(row.data_hash)||digest(row)!==row.data_hash)U.fail('corrupt',503); const record=exact(JSON.parse(row.data),RECORD_KEYS),lists=parseLists(record); if(!Number.isSafeInteger(record.version)||record.version<1||record.version!==row.version||record.simulation!==true||!instant(record.updatedAt)||record.updatedAt!==row.updated_at||U.canonical(lists.favorites)!==U.canonical(record.favorites)||U.canonical(lists.savedSearches)!==U.canonical(record.savedSearches)||U.canonical(record)!==row.data)U.fail('corrupt',503); return record; }catch(_){U.fail('corrupt',503);} } // Backups made before discovery tools have no table and migrate empty on open. function verifyStoredDiscoveryTools(db){ if(!db.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name='discovery_tools'").get())return; const owners=new Set(); for(const row of db.prepare('SELECT * FROM discovery_tools').all()){ verifyStoredDiscoveryTool(row); if(owners.has(row.user_id)||!db.prepare('SELECT id FROM users WHERE id=?').get(row.user_id))U.fail('corrupt',503); owners.add(row.user_id); } } function createDiscovery(store,{now=()=>new Date().toISOString()}={}){ const {get,run,transaction,security}=store; const empty=()=>({version:0,favorites:[],savedSearches:[],updatedAt:null,simulation:true}); function read(user){ const row=get('SELECT * FROM discovery_tools WHERE user_id=?',user.id); return row?verifyStoredDiscoveryTool(row):empty(); } function save(user,input){ exact(input,INPUT_KEYS); if(!Number.isSafeInteger(input.expectedVersion)||input.expectedVersion<0)U.fail('invalid'); const lists=parseLists(input); return transaction(()=>{ const row=get('SELECT * FROM discovery_tools WHERE user_id=?',user.id),current=row?verifyStoredDiscoveryTool(row):empty(); if(current.version!==input.expectedVersion||current.version===Number.MAX_SAFE_INTEGER)U.fail('conflict',409); const record={version:current.version+1,...lists,updatedAt:now(),simulation:true}; const next={user_id:user.id,data:U.canonical(record),version:record.version,updated_at:record.updatedAt}; next.data_hash=digest(next);verifyStoredDiscoveryTool(next); if(row){ const result=run('UPDATE discovery_tools SET data=?,data_hash=?,version=?,updated_at=? WHERE user_id=? AND version=?',next.data,next.data_hash,next.version,next.updated_at,user.id,current.version); if(result.changes!==1)U.fail('conflict',409); }else run('INSERT INTO discovery_tools(user_id,data,data_hash,version,updated_at) VALUES (?,?,?,?,?)',next.user_id,next.data,next.data_hash,next.version,next.updated_at); security(user.id,'discovery_tools_updated',{version:record.version,favoritesCount:record.favorites.length,savedSearchesCount:record.savedSearches.length},record.updatedAt); return record; }); } return {get:read,save}; } module.exports={createDiscovery,verifyStoredDiscoveryTool,verifyStoredDiscoveryTools};