'use strict';
const test=require('node:test');
const assert=require('node:assert/strict');
const fs=require('node:fs');
const os=require('node:os');
const path=require('node:path');
const {spawnSync}=require('node:child_process');
const {DatabaseSync}=require('node:sqlite');
const {createApp}=require('../server/app.cjs');
const {createDiscovery,verifyStoredDiscoveryTool,verifyStoredDiscoveryTools}=require('../server/discovery.cjs');
const C=require('../server/catalog.cjs');
const U=require('../server/util.cjs');
const PASSWORD='Fictional discovery fixture password 2026!';
const MANAGE=path.resolve(__dirname,'../scripts/manage.cjs');
const EMPTY={version:0,favorites:[],savedSearches:[],updatedAt:null,simulation:true};
const OFFERS=C.catalog().offers.map(offer=>offer.id);
const KEYS=['version','favorites','savedSearches','updatedAt','simulation'].sort();
let encodedPassword;
const error=(code,status)=>e=>{assert.equal(e.code,code);assert.equal(e.status||422,status);return true;};
const search=(extra={})=>({id:'saved_search_001',name:'Private Dubai search',query:'Private credit in Dubai',country:'AE',category:'Private credit',benefit:'discount',sort:'featured',favoritesOnly:false,...extra});
const input=(extra={})=>({expectedVersion:0,favorites:[OFFERS[0],OFFERS[3]],savedSearches:[search()],...extra});
async function fixture(t){
const dir=fs.mkdtempSync(path.join(os.tmpdir(),'glemo-discovery-test-'));
let app,base,clock=Date.parse('2026-10-22T12:00:00.000Z');
const now=()=>new Date(clock).toISOString();
async function reopen(){app=await createApp({dataDir:dir,now});base=await app.listen();}
async function close(){if(app){await app.close();app=null;}}
t.after(async()=>{await close();fs.rmSync(dir,{recursive:true,force:true});});
await reopen();
encodedPassword||=U.passwordHash(PASSWORD);
const passwordHash=await encodedPassword;
function person(alias,role,orgId){
const id=U.id();
if(!orgId){orgId=U.id();app.store.run('INSERT INTO organizations VALUES (?,?,?)',orgId,'DEMO '+alias,now());}
app.store.run('INSERT INTO users VALUES (?,?,?,?,?,?,?)',id,alias,role,orgId,passwordHash,1,now());
app.store.run('INSERT INTO profiles VALUES (?,?,?,?)',id,JSON.stringify({completed:false,history:'DEMO PRIVATE PROFILE '+alias}),0,now());
return app.auth.publicUser(app.store.get('SELECT * FROM users WHERE id=?',id));
}
const users=Object.fromEntries(['admin','buyer','holder','compliance','rails','auditor'].map(role=>[role,person('discovery-'+role,role)]));
const other=person('discovery-other','buyer'),sameOrg=person('discovery-same-org','buyer',users.buyer.orgId);
function client(user){
const raw=user?U.token():null,csrf=user?U.token():null;
if(user)app.store.run('INSERT INTO sessions VALUES (?,?,?,?,?,?)',U.hash(raw),user.id,csrf,now(),now(),new Date(clock+12*3600000).toISOString());
async function request(method,route,body,extra={},rawBody=false){
const res=await fetch(base+route,{method,headers:{Origin:base,...(user?{Cookie:'glemo_shared_local='+raw,'X-CSRF-Token':csrf}:{}),...(body===undefined?{}:{'Content-Type':'application/json'}),...extra},body:body===undefined?undefined:rawBody?body:JSON.stringify(body)});
return {status:res.status,value:await res.json(),headers:res.headers};
}
return {request,raw,csrf};
}
return {dir,users,other,sameOrg,person,client,close,reopen,now,advance:ms=>{clock+=ms;},get app(){return app;},get store(){return app.store;},get discovery(){return app.discovery;},get base(){return base;}};
}
test('discovery: every authenticated role has a private default and can save metadata only',async t=>{
const f=await fixture(t);
for(const role of Object.keys(f.users))await t.test(role,async()=>{
const user=f.users[role],client=f.client(user),initial=await client.request('GET','/api/discovery-tools');
assert.equal(initial.status,200);assert.deepEqual(initial.value,EMPTY);
assert.equal(f.store.get('SELECT count(*) AS n FROM discovery_tools WHERE user_id=?',user.id).n,0);
const saved=await client.request('POST','/api/discovery-tools',input());
assert.equal(saved.status,200);assert.deepEqual(Object.keys(saved.value).sort(),KEYS);
assert.deepEqual(saved.value,{version:1,favorites:[OFFERS[0],OFFERS[3]],savedSearches:[search()],updatedAt:f.now(),simulation:true});
assert.deepEqual((await client.request('GET','/api/discovery-tools')).value,saved.value);
assert.equal(saved.headers.get('cache-control'),'no-store');assert.equal(saved.headers.get('x-content-type-options'),'nosniff');
const fresh=f.discovery.get(f.other);fresh.favorites.push(OFFERS[0]);assert.deepEqual(f.discovery.get(f.other),EMPTY);
});
for(const table of ['cases','members','commands','external_evidence','case_audit','notifications','rehearsals','asset_requests'])assert.equal(f.store.get('SELECT count(*) AS n FROM '+table).n,0,table);
const audit=f.store.all('SELECT action,detail FROM security_audit');assert.equal(audit.length,6);
for(const event of audit){assert.equal(event.action,'discovery_tools_updated');assert.deepEqual(JSON.parse(event.detail),{version:1,favoritesCount:2,savedSearchesCount:1});}
for(const privateText of ['Private Dubai search','Private credit in Dubai',OFFERS[0],'saved_search_001'])assert(!JSON.stringify(audit).includes(privateText));
});
test('discovery API: owner isolation applies even to administrators and same-organization users',async t=>{
const f=await fixture(t),owner=f.client(f.users.buyer),saved=(await owner.request('POST','/api/discovery-tools',input())).value;
for(const user of [f.other,f.sameOrg,...Object.values(f.users).filter(u=>u.id!==f.users.buyer.id)])await t.test(user.role+' '+user.alias,async()=>{
const client=f.client(user);
assert.deepEqual((await client.request('GET','/api/discovery-tools')).value,EMPTY);
assert.deepEqual((await client.request('GET','/api/discovery-tools?userId='+f.users.buyer.id)).value,EMPTY);
for(const route of ['/api/discovery-tools/'+f.users.buyer.id,'/api/admin/discovery-tools','/api/admin/discovery-tools/'+f.users.buyer.id]){
assert.equal((await client.request('GET',route)).status,404);
assert.equal((await client.request('POST',route,input())).status,404);
}
const own=await client.request('POST','/api/discovery-tools',input({favorites:[OFFERS[1]],savedSearches:[]}));
assert.equal(own.status,200);assert.deepEqual(own.value.favorites,[OFFERS[1]]);
assert.deepEqual((await owner.request('GET','/api/discovery-tools')).value,saved);
});
for(const secret of ['userId','user_id','ownerId','orgId','alias','password','csrf',f.users.buyer.id,f.users.buyer.orgId,'PRIVATE PROFILE'])assert(!JSON.stringify(saved).includes(secret));
});
test('discovery API: authentication, Origin, CSRF, body limits and HTTP methods are enforced',async t=>{
const f=await fixture(t),buyer=f.client(f.users.buyer),anonymous=f.client();
assert.equal((await anonymous.request('GET','/api/discovery-tools')).status,401);
assert.equal((await anonymous.request('POST','/api/discovery-tools',input())).status,401);
for(const headers of [{'X-CSRF-Token':''},{'X-CSRF-Token':'wrong'},{'X-CSRF-Token':U.token()},{Origin:'https://foreign.example'},{'Sec-Fetch-Site':'cross-site'}])assert.equal((await buyer.request('POST','/api/discovery-tools',input(),headers)).status,403);
assert.equal((await buyer.request('POST','/api/discovery-tools',input(),{'Content-Type':'text/plain'})).status,415);
assert.equal((await buyer.request('POST','/api/discovery-tools','{',{},true)).status,400);
assert.equal((await buyer.request('POST','/api/discovery-tools',input({savedSearches:[search({query:'x'.repeat(33000)})]}))).status,413);
for(const method of ['DELETE','PATCH','PUT'])assert.equal((await buyer.request(method,'/api/discovery-tools')).status,405);
assert.equal(f.store.get('SELECT count(*) AS n FROM discovery_tools').n,0);
assert.equal((await buyer.request('POST','/api/discovery-tools',input())).status,200);
f.store.run('UPDATE users SET active=0 WHERE id=?',f.users.buyer.id);
assert.equal((await buyer.request('GET','/api/discovery-tools')).status,401);
assert.equal((await buyer.request('POST','/api/discovery-tools',input({expectedVersion:1}))).status,401);
const expired=f.client(f.other);f.advance(13*3600000);
assert.equal((await expired.request('GET','/api/discovery-tools')).status,401);
const revoked=f.client(f.users.holder);f.app.auth.logout(f.app.auth.session(revoked.raw));
assert.equal((await revoked.request('POST','/api/discovery-tools',input())).status,401);
});
test('discovery API: strict top-level DTO rejects spoofing, missing fields and invalid versions',async t=>{
const f=await fixture(t),client=f.client(f.users.buyer);
const invalid={'null':null,'array':[],'string':'metadata'};
for(const field of ['expectedVersion','favorites','savedSearches']){const body=input();delete body[field];invalid['missing '+field]=body;}
for(const field of ['userId','user_id','ownerId','owner','role','admin','orgId','updatedAt','version','simulation','contact','notifications'])invalid['unknown '+field]=input({[field]:'spoof'});
for(const value of [-1,0.5,'0',null,true,{},[],Number.MAX_SAFE_INTEGER+1])invalid['version '+JSON.stringify(value)]=input({expectedVersion:value});
for(const [name,body]of Object.entries(invalid))await t.test(name,async()=>{
const r=await client.request('POST','/api/discovery-tools',body);assert.equal(r.status,422,JSON.stringify(r.value));
});
const proto=JSON.parse(JSON.stringify(input()).replace('"expectedVersion":0','"__proto__":{"admin":true},"expectedVersion":0'));
assert.equal((await client.request('POST','/api/discovery-tools',proto)).status,422);
assert.equal((await client.request('POST','/api/discovery-tools',input({expectedVersion:Number.MAX_SAFE_INTEGER}))).status,409);
assert.equal(f.store.get('SELECT count(*) AS n FROM discovery_tools').n,0);
});
test('discovery: favorites must be unique real catalog IDs, never arbitrary company or case IDs',async t=>{
const f=await fixture(t);
for(const [name,value]of Object.entries({null:null,string:OFFERS[0],object:{id:OFFERS[0]},boolean:true,unknown:['DEMO-OFFER-999'],company:['DEMO-SELLER-001'],case:['PILOT-123'],number:[1],nested:[[OFFERS[0]]],objectItem:[{id:OFFERS[0]}],duplicate:[OFFERS[0],OFFERS[0]],tooMany:Array(33).fill(OFFERS[0]),untrimmed:[' '+OFFERS[0]],lowercase:[OFFERS[0].toLowerCase()]}))await t.test(name,()=>assert.throws(()=>f.discovery.save(f.users.buyer,input({favorites:value})),error('invalid',422)));
const accepted=f.discovery.save(f.users.buyer,input({favorites:OFFERS.slice(),savedSearches:[]}));
assert.deepEqual(accepted.favorites,OFFERS);
assert.deepEqual(f.discovery.save(f.users.buyer,{expectedVersion:1,favorites:[],savedSearches:[]}).favorites,[]);
});
test('discovery: saved search strict shape, IDs, enums, lengths and limits are validated',async t=>{
const f=await fixture(t),invalid={null:null,string:'saved',object:{},tooMany:Array.from({length:11},(_,i)=>search({id:'saved_search_'+String(i).padStart(3,'0')})),duplicate:[search(),search()]};
for(const field of Object.keys(search())){const value=search();delete value[field];invalid['missing '+field]=[value];}
for(const field of ['ownerId','userId','createdAt','notification','email','interval','enabled'])invalid['unknown '+field]=[search({[field]:'spoof'})];
for(const value of ['', 'x'.repeat(11),'x'.repeat(91),'has spaces in id','saved/search/001',null,1,{},true])invalid['id '+JSON.stringify(value)]=[search({id:value})];
for(const value of ['', ' '.repeat(10),'x'.repeat(61),null,1,{},true,[]])invalid['name '+JSON.stringify(value)]=[search({name:value})];
for(const value of ['x'.repeat(201),null,1,{},true,[]])invalid['query '+JSON.stringify(value)]=[search({query:value})];
for(const [key,value]of [['country','BR'],['country',null],['category','Other'],['category',[]],['benefit','airdrop'],['benefit',false],['sort','newest'],['sort',{}],['favoritesOnly','false'],['favoritesOnly',0],['favoritesOnly',null]])invalid[key+' '+JSON.stringify(value)]=[search({[key]:value})];
invalid['null search']=[null];invalid['array search']=[[]];invalid['string search']=['search'];
for(const [name,savedSearches]of Object.entries(invalid))await t.test(name,()=>assert.throws(()=>f.discovery.save(f.users.buyer,input({savedSearches})),error('invalid',422)));
assert.equal(f.store.get('SELECT count(*) AS n FROM discovery_tools').n,0);
const savedSearches=Array.from({length:10},(_,i)=>search({id:'A_-'.repeat(4)+i,name:' '+('搜'.repeat(60))+' ',query:' '+('x'.repeat(200))+' ',country:['','AE','SG','US','HK','GB'][i%6],category:['','Real estate','Private credit','Treasury','Commodities'][i%5],benefit:['','discount','time','volume','points'][i%5],sort:['featured','minTicketAsc','minTicketDesc','closing'][i%4],favoritesOnly:i%2===0}));
const record=f.discovery.save(f.users.buyer,input({savedSearches}));
assert.equal(record.savedSearches.length,10);
for(const value of record.savedSearches){assert.equal(value.name.length,60);assert.equal(value.query.length,200);assert.deepEqual(Object.keys(value).sort(),Object.keys(search()).sort());}
const plain=f.discovery.save(f.other,input({savedSearches:[search({id:'A_-'.repeat(30),name:'DEMO not HTML',query:'',country:'',category:'',benefit:'',favoritesOnly:true})]}));
assert.equal(plain.savedSearches[0].name,'DEMO not HTML');assert.equal(plain.savedSearches[0].query,'');
});
test('discovery API: versioned writes use CAS, including concurrent first insert and identical retries',async t=>{
const f=await fixture(t),client=f.client(f.users.buyer),route='/api/discovery-tools';
const first=await Promise.all(Array.from({length:12},(_,i)=>client.request('POST',route,input({favorites:[OFFERS[i%OFFERS.length]]}))));
assert.equal(first.filter(r=>r.status===200).length,1);assert.equal(first.filter(r=>r.status===409).length,11);
const current=(await client.request('GET',route)).value;assert.equal(current.version,1);
assert.equal((await client.request('POST',route,input({favorites:current.favorites}))).status,409);
f.advance(1000);
const next=await Promise.all(Array.from({length:12},(_,i)=>client.request('POST',route,input({expectedVersion:1,savedSearches:[search({name:'DEMO choice '+i})]}))));
assert.equal(next.filter(r=>r.status===200).length,1);assert.equal(next.filter(r=>r.status===409).length,11);
const latest=(await client.request('GET',route)).value;assert.equal(latest.version,2);assert.equal(latest.updatedAt,f.now());
assert.deepEqual(latest,next.find(r=>r.status===200).value);
assert.equal(f.store.get('SELECT count(*) AS n FROM discovery_tools').n,1);
assert.equal(f.store.get("SELECT count(*) AS n FROM security_audit WHERE action='discovery_tools_updated'").n,2);
const identical=await client.request('POST',route,{expectedVersion:2,favorites:latest.favorites,savedSearches:latest.savedSearches});
assert.equal(identical.status,200);assert.equal(identical.value.version,3);
});
test('discovery: separate SQLite connections serialize the same owner version',async t=>{
const f=await fixture(t),otherApp=await createApp({dataDir:f.dir,now:f.now});t.after(()=>otherApp.close());
const prior=f.discovery.get(f.users.buyer);assert.equal(prior.version,0);
const saved=otherApp.discovery.save(f.users.buyer,input());assert.equal(saved.version,1);
assert.throws(()=>f.discovery.save(f.users.buyer,input()),error('conflict',409));
assert.deepEqual(f.discovery.get(f.users.buyer),saved);
f.discovery.save(f.users.buyer,input({expectedVersion:1,favorites:[]}));
assert.throws(()=>otherApp.discovery.save(f.users.buyer,input({expectedVersion:1})),error('conflict',409));
});
test('discovery: financial pause permits metadata writes and does not generate deal or notification activity',async t=>{
const f=await fixture(t);f.store.run("UPDATE settings SET value='true' WHERE key='paused'");
for(const user of Object.values(f.users)){
const client=f.client(user),r=await client.request('POST','/api/discovery-tools',input());
assert.equal(r.status,200);assert.equal(r.value.version,1);
assert.equal((await client.request('POST','/api/discovery-tools',input({expectedVersion:1,favorites:[],savedSearches:[]}))).status,200);
}
assert.equal(f.app.service.paused(),true);
for(const table of ['cases','commands','members','notifications','rehearsals','asset_requests','external_evidence','case_audit'])assert.equal(f.store.get('SELECT count(*) AS n FROM '+table).n,0);
});
test('discovery: database update and metadata-only audit roll back atomically',async t=>{
const f=await fixture(t),broken=createDiscovery({...f.store,security(){throw Error('DEMO audit unavailable');}},{now:f.now});
assert.throws(()=>broken.save(f.users.buyer,input()),/audit unavailable/);assert.deepEqual(f.discovery.get(f.users.buyer),EMPTY);
assert.equal(f.store.get('SELECT count(*) AS n FROM discovery_tools').n,0);
const record=f.discovery.save(f.users.buyer,input());
assert.throws(()=>broken.save(f.users.buyer,input({expectedVersion:1,favorites:[]})),/audit unavailable/);
assert.deepEqual(f.discovery.get(f.users.buyer),record);
assert.equal(f.store.get('SELECT count(*) AS n FROM security_audit').n,1);
});
function rehash(row){row.data_hash=U.hash(U.canonical({userId:row.user_id,data:row.data}));return row;}
function putRow(store,row,originalOwner=row.user_id){store.run('UPDATE discovery_tools SET user_id=?,data=?,data_hash=?,version=?,updated_at=? WHERE user_id=?',row.user_id,row.data,row.data_hash,row.version,row.updated_at,originalOwner);}
test('discovery: STRICT schema, positive versions, foreign keys and unique owner prevent malformed writes',async t=>{
const f=await fixture(t);f.discovery.save(f.users.buyer,input());
assert.equal(f.store.all('PRAGMA table_list').find(row=>row.name==='discovery_tools').strict,1);
assert.throws(()=>f.store.run('UPDATE discovery_tools SET version=0.5 WHERE user_id=?',f.users.buyer.id),/INTEGER/);
assert.throws(()=>f.store.run('UPDATE discovery_tools SET version=0 WHERE user_id=?',f.users.buyer.id),/CHECK/);
assert.throws(()=>f.store.run('UPDATE discovery_tools SET user_id=? WHERE user_id=?',U.id(),f.users.buyer.id),/FOREIGN KEY/);
assert.throws(()=>f.store.run('INSERT INTO discovery_tools SELECT * FROM discovery_tools WHERE user_id=?',f.users.buyer.id),/UNIQUE/);
});
test('discovery API: read/write integrity rejects corrupt private rows without disclosing them',async t=>{
const f=await fixture(t),owner=f.client(f.users.buyer),other=f.client(f.other),admin=f.client(f.users.admin);
f.discovery.save(f.users.buyer,input());const original=f.store.get('SELECT * FROM discovery_tools WHERE user_id=?',f.users.buyer.id);
const bad={
'unhashed data':row=>{row.data+=' ';},
'bad digest format':row=>{row.data_hash='x'.repeat(64);},
'invalid JSON rehashed':row=>{row.data='{';rehash(row);},
'owner rebound':row=>{row.user_id=f.other.id;},
'row version mismatch':row=>{row.version=2;},
'row time mismatch':row=>{row.updated_at='2026-10-23T12:00:00.000Z';},
'noncanonical JSON':row=>{row.data=JSON.stringify(JSON.parse(row.data),null,2);rehash(row);}
};
for(const [name,change]of Object.entries({
'missing field':record=>{delete record.updatedAt;},
'private extra key':record=>{record.ownerId='DEMO PRIVATE';},
'not simulated':record=>{record.simulation=false;},
'invalid version':record=>{record.version='1';},
'invalid timestamp':record=>{record.updatedAt='yesterday';},
'noncanonical timestamp':record=>{record.updatedAt='2026-10-22T12:00:00Z';},
'unknown offer':record=>{record.favorites=['DEMO-OFFER-999'];},
'duplicate favorite':record=>{record.favorites.push(record.favorites[0]);},
'too many searches':record=>{record.savedSearches=Array.from({length:11},(_,i)=>search({id:'saved_search_'+i}));},
'duplicate search ID':record=>{record.savedSearches.push({...record.savedSearches[0]});},
'invalid category':record=>{record.savedSearches[0].category='crypto';},
'invalid country':record=>{record.savedSearches[0].country='BR';},
'invalid benefit':record=>{record.savedSearches[0].benefit='all';},
'invalid sorting':record=>{record.savedSearches[0].sort='random';},
'untrimmed name':record=>{record.savedSearches[0].name+=' ';},
'untrimmed query':record=>{record.savedSearches[0].query+=' ';},
'invalid boolean':record=>{record.savedSearches[0].favoritesOnly='true';}
}))bad[name]=row=>{const record=JSON.parse(row.data);change(record);row.data=U.canonical(record);rehash(row);};
for(const [name,change]of Object.entries(bad))await t.test(name,async()=>{
const row={...original};change(row);putRow(f.store,row,original.user_id);
assert.throws(()=>verifyStoredDiscoveryTool(row),error('corrupt',503));
const affected=name==='owner rebound'?other:owner;
const result=await affected.request('GET','/api/discovery-tools');assert.equal(result.status,503);
assert.deepEqual(Object.keys(result.value),['error']);assert(!JSON.stringify(result.value).includes('Private Dubai'));
assert.equal((await affected.request('POST','/api/discovery-tools',input({expectedVersion:1}))).status,503);
assert.deepEqual((await admin.request('GET','/api/discovery-tools')).value,EMPTY);
assert.equal((await admin.request('GET','/api/admin/discovery-tools')).status,404);
putRow(f.store,original,row.user_id);
});
assert.equal(f.discovery.get(f.users.buyer).version,1);
});
const credentials=f=>f.store.all('SELECT id,role,password_hash FROM users ORDER BY id').map(({password_hash,...row})=>({...row,passwordDigest:U.hash(password_hash)}));
const discoveryRows=f=>f.store.all('SELECT * FROM discovery_tools ORDER BY user_id');
function manage(dir,...args){const r=spawnSync(process.execPath,[MANAGE,...args],{env:{...process.env,PILOT_DATA_DIR:dir,PUBLIC_ORIGIN:'http://127.0.0.1:8816'},encoding:'utf8',timeout:15000});assert.equal(r.error,undefined);assert.equal(r.signal,null);return r;}
function noRestoreDebris(dir){assert.equal(fs.existsSync(path.join(dir,'maintenance.lock')),false);assert.deepEqual(fs.readdirSync(dir).filter(name=>name.startsWith('restore-')),[]);}
test('discovery recovery: restart and backup restore retain private metadata, versions and credentials',async t=>{
const source=await fixture(t),target=await fixture(t);
source.discovery.save(source.users.buyer,input());source.discovery.save(source.users.admin,input({favorites:[OFFERS[1]],savedSearches:[]}));
source.advance(1000);source.discovery.save(source.users.buyer,input({expectedVersion:1,savedSearches:[search({name:'DEMO latest private brief'})]}));
source.client(source.users.buyer);
const expected=discoveryRows(source),accounts=credentials(source),audit=source.store.all('SELECT * FROM security_audit');
await source.close();await source.reopen();
assert.deepEqual(discoveryRows(source),expected);assert.deepEqual(credentials(source),accounts);assert.deepEqual(source.store.all('SELECT * FROM security_audit'),audit);
assert.throws(()=>source.discovery.save(source.users.buyer,input({expectedVersion:1})),error('conflict',409));
const snapshot=await source.store.snapshot(),file=path.join(source.dir,'backups',snapshot.name),digest=U.hash(fs.readFileSync(file));
source.discovery.save(source.users.buyer,input({expectedVersion:2,favorites:[],savedSearches:[]}));target.discovery.save(target.users.buyer,input());
await source.close();await target.close();
const result=manage(target.dir,'restore',file);assert.equal(result.status,0,result.stderr);noRestoreDebris(target.dir);
await target.reopen();assert.deepEqual(discoveryRows(target),expected);assert.deepEqual(credentials(target),accounts);
assert.equal(target.store.get('SELECT count(*) AS n FROM sessions').n,0);
assert.equal(target.discovery.get(source.users.buyer).version,2);assert.deepEqual(target.discovery.get(source.other),EMPTY);
const logged=await target.app.auth.login({alias:source.users.buyer.alias,password:PASSWORD},'DEMO-LOCAL');assert.equal(logged.user.id,source.users.buyer.id);
assert.equal(U.hash(fs.readFileSync(file)),digest);
assert.equal(fs.readdirSync(path.join(target.dir,'backups')).filter(name=>name.endsWith('.sqlite')).length,1);
});
test('discovery recovery: backups without discovery_tools are accepted and migrate empty',async t=>{
const source=await fixture(t),target=await fixture(t);source.discovery.save(source.users.buyer,input());target.discovery.save(target.users.buyer,input());
const accounts=credentials(source),snapshot=await source.store.snapshot(),file=path.join(source.dir,'backups',snapshot.name),old=new DatabaseSync(file);
old.exec('DROP TABLE discovery_tools');assert.doesNotThrow(()=>verifyStoredDiscoveryTools(old));old.close();const digest=U.hash(fs.readFileSync(file));
await source.close();await target.close();
const result=manage(target.dir,'restore',file);assert.equal(result.status,0,result.stderr);noRestoreDebris(target.dir);
await target.reopen();assert.deepEqual(discoveryRows(target),[]);assert.deepEqual(credentials(target),accounts);assert.deepEqual(target.discovery.get(source.users.buyer),EMPTY);
assert.equal(target.discovery.save(source.users.buyer,input()).version,1);assert.equal(U.hash(fs.readFileSync(file)),digest);
});
test('discovery recovery: logical corruption and orphan owners reject backups without altering the target',async t=>{
const source=await fixture(t),target=await fixture(t);source.discovery.save(source.users.buyer,input());target.discovery.save(target.users.buyer,input());
const expected=discoveryRows(target),accounts=credentials(target),snapshot=await source.store.snapshot(),file=path.join(source.dir,'backups',snapshot.name);
await source.close();await target.close();
const original=fs.readFileSync(file),before=U.hash(fs.readFileSync(path.join(target.dir,'pilot.sqlite')));
for(const [name,change]of Object.entries({
'invalid JSON':row=>{row.data='{';rehash(row);},
'logical invalid favorite':row=>{const r=JSON.parse(row.data);r.favorites=['DEMO-OFFER-999'];row.data=U.canonical(r);rehash(row);},
'owner rebound':row=>{row.user_id=source.other.id;},
'orphan owner':row=>{row.user_id=U.id();rehash(row);},
'row version mismatch':row=>{row.version=2;}
}))await t.test(name,()=>{
fs.writeFileSync(file,original);const db=new DatabaseSync(file);
try{db.exec('PRAGMA foreign_keys=OFF');const row=db.prepare('SELECT * FROM discovery_tools WHERE user_id=?').get(source.users.buyer.id);change(row);putRow({run:(sql,...args)=>db.prepare(sql).run(...args)},row,source.users.buyer.id);
assert.throws(()=>verifyStoredDiscoveryTools(db),error('corrupt',503));
}finally{db.close();}
const digest=U.hash(fs.readFileSync(file)),result=manage(target.dir,'restore',file);
assert.equal(result.status,1);assert.match(result.stderr,/corrupt|Invalid backup/);noRestoreDebris(target.dir);
assert.equal(U.hash(fs.readFileSync(file)),digest);assert.equal(U.hash(fs.readFileSync(path.join(target.dir,'pilot.sqlite'))),before);
});
await target.reopen();assert.deepEqual(discoveryRows(target),expected);assert.deepEqual(credentials(target),accounts);
});
test('discovery recovery: duplicate owners in a malformed table fail logical backup validation',async t=>{
const f=await fixture(t);f.discovery.save(f.users.buyer,input());
const row=f.store.get('SELECT * FROM discovery_tools WHERE user_id=?',f.users.buyer.id);
f.store.db.exec('DROP TABLE discovery_tools; CREATE TABLE discovery_tools(user_id TEXT,data TEXT,data_hash TEXT,version INTEGER,updated_at TEXT)');
for(let i=0;i<2;i++)f.store.run('INSERT INTO discovery_tools VALUES (?,?,?,?,?)',row.user_id,row.data,row.data_hash,row.version,row.updated_at);
assert.throws(()=>verifyStoredDiscoveryTools(f.store.db),error('corrupt',503));
});
test('discovery recovery: staged copy is revalidated after the source snapshot passed validation',async t=>{
const source=await fixture(t),target=await fixture(t);source.discovery.save(source.users.buyer,input());target.discovery.save(target.users.buyer,input());
const expected=discoveryRows(target),snapshot=await source.store.snapshot(),file=path.join(source.dir,'backups',snapshot.name),digest=U.hash(fs.readFileSync(file));
await source.close();await target.close();const before=U.hash(fs.readFileSync(path.join(target.dir,'pilot.sqlite')));
const script=`const fs=require('node:fs'),path=require('node:path'),{DatabaseSync}=require('node:sqlite');
const copy=fs.copyFileSync;fs.copyFileSync=function(from,to,...args){const r=copy(from,to,...args);if(path.basename(to).startsWith('restore-')){const db=new DatabaseSync(to);try{db.prepare("UPDATE discovery_tools SET data_hash=? WHERE user_id=?").run('0'.repeat(64),${JSON.stringify(source.users.buyer.id)});}finally{db.close();}}return r;};
process.argv=[process.execPath,${JSON.stringify(MANAGE)},'restore',${JSON.stringify(file)}];require(${JSON.stringify(MANAGE)}).main().catch(e=>{console.error(e.code||e.message);process.exitCode=1;});`;
const result=spawnSync(process.execPath,['--eval',script],{env:{...process.env,PILOT_DATA_DIR:target.dir},encoding:'utf8',timeout:15000});
assert.equal(result.status,1,result.stderr);assert.match(result.stderr,/corrupt/);noRestoreDebris(target.dir);
assert.equal(U.hash(fs.readFileSync(file)),digest);assert.equal(U.hash(fs.readFileSync(path.join(target.dir,'pilot.sqlite'))),before);
await target.reopen();assert.deepEqual(discoveryRows(target),expected);
});