seller.mjs (12581B)
1 import assert from 'node:assert/strict'; 2 import {createServer} from 'node:http'; 3 import {readFile} from 'node:fs/promises'; 4 import {createRequire} from 'node:module'; 5 import {resolve, sep} from 'node:path'; 6 7 const [moduleRoot, packageDir, engine, previousPackageDir] = process.argv.slice(2); 8 assert(moduleRoot && packageDir && previousPackageDir && ['chromium','firefox','webkit'].includes(engine)); 9 const playwright = createRequire(resolve(moduleRoot,'package.json'))('playwright'); 10 const root = resolve(packageDir), previousRoot = resolve(previousPackageDir); 11 async function workflow({WorkspaceFixture}, previous) { 12 let phase='legacy setup'; 13 try { 14 const tests = []; 15 const check = (condition) => { if (!condition) throw Error('seller scope assertion'); }; 16 const refuses = async (action, code) => { 17 try { await action(); } catch (error) { 18 if (String(error) !== code) throw Error('expected ' + code + ', received ' + String(error)); 19 return; 20 } 21 throw Error('expected ' + code); 22 }; 23 const old = await previous.WorkspaceFixture.create(244); 24 const oldFingerprint = old.fingerprint(), oldSelection = old.selection(), oldProof = old.proof(); 25 const original = Array.from(await old.admit(243, false)); 26 const originalPlanWire = Uint8Array.from(await old.new_plan(243)); 27 const originalPlan = Array.from(await old.bind_plan(243, originalPlanWire)); 28 const obtained = await old.obtain(243, 0, false); 29 const originalClaim = Array.from(obtained.original_claim()); 30 const originalCapture = Array.from(await old.capture(obtained)); 31 await old.close(); 32 phase='published private reopen'; 33 const current = await WorkspaceFixture.open(244, oldFingerprint, oldSelection, oldProof); 34 check(!await current.is_seller()); 35 check(JSON.stringify(Array.from(await current.query(243))) === JSON.stringify(original)); 36 check(JSON.stringify(Array.from(await current.admit(243, false))) === JSON.stringify(original)); 37 check(JSON.stringify(Array.from(await current.plan_query(243))) === JSON.stringify(originalPlan)); 38 check(JSON.stringify(Array.from(await current.bind_plan(243, originalPlanWire))) === JSON.stringify(originalPlan)); 39 check(JSON.stringify(Array.from(await current.attempt(243, 0))) === JSON.stringify(originalClaim)); 40 check(JSON.stringify(Array.from(await current.captured(243, 0))) === JSON.stringify(originalCapture)); 41 await refuses(() => current.obtain(243, 0, false), 'retained_no_dispatch'); 42 await current.close(); 43 tests.push('original published buyer T0, T1, claim and obtained capture reopen without replacement or reissue'); 44 phase='seller public T0/T1'; 45 const seller = await WorkspaceFixture.create_seller(245); 46 check(await seller.is_seller()); 47 check(await seller.authenticate() === 1); 48 await refuses(() => seller.wrong_proof(), 'unauthorized'); 49 const preparation = Array.from(await seller.admit(242, false)); 50 const publicPreparation=Array.from(await seller.admit_public(244)); 51 const publicPlan=Array.from(await seller.bind_public(244)); 52 check(JSON.stringify(Array.from(await seller.admit_public(244)))===JSON.stringify(publicPreparation)); 53 check(JSON.stringify(Array.from(await seller.bind_public(244)))===JSON.stringify(publicPlan)); 54 await refuses(()=>seller.admit_public(245),'stale_state'); 55 check((await seller.query(245)).length===0); 56 phase='public signing'; 57 const publicOutput=await seller.obtain(244,2,false); 58 check(publicOutput.malformed_output_refused()); 59 seller.set_time(2000); 60 phase='late public capture'; 61 const publicCapture=Array.from(await seller.capture(publicOutput)); 62 seller.set_time(1500); 63 phase='late public installation'; 64 const publicInstallation=await seller.install_public(244); 65 check(await seller.install_public(244)===publicInstallation); 66 check(JSON.parse(publicInstallation).observed===null); 67 check(JSON.parse(publicInstallation).installed_at==='1500'); 68 check(JSON.parse(publicInstallation).capture===publicCapture.slice(0,32).map(value=>value.toString(16).padStart(2,'0')).join('')); 69 tests.push('public T0/T1 replay, coordinate refusal, real verified S, late null-time capture and exactly-once T2 after signing expiry'); 70 const fingerprint = seller.fingerprint(), selection = seller.selection(), proof = seller.proof(); 71 await seller.close(); 72 phase='retained public reopen'; 73 let reopened = await WorkspaceFixture.open(245, fingerprint, selection, proof); 74 reopened.set_time(1500); 75 check(await reopened.is_seller()); 76 check(JSON.stringify(Array.from(await reopened.query(242))) === JSON.stringify(preparation)); 77 check(JSON.stringify(Array.from(await reopened.query(244)))===JSON.stringify(publicPreparation)); 78 check(JSON.stringify(Array.from(await reopened.public_plan_query(244)))===JSON.stringify(publicPlan)); 79 check(await reopened.install_public(244)===publicInstallation); 80 check(JSON.stringify(Array.from(await reopened.captured(244,2)))===JSON.stringify(publicCapture)); 81 await refuses(()=>reopened.obtain(244,2,false),'retained_no_dispatch'); 82 tests.push('actual protected close/reopen retains seller scope and original private/public preparation and plan'); 83 const originalSnapshot=await reopened.public_snapshot(244); 84 const namespace=reopened.data_namespace(),coordinate=Array.from(await reopened.public_coordinate_key(244)); 85 const openRaw=()=>new Promise((resolve,reject)=>{const request=indexedDB.open(namespace,1);request.onsuccess=()=>resolve(request.result);request.onerror=reject;request.onupgradeneeded=()=>request.transaction.abort();}); 86 const readRows=async()=>{const db=await openRaw();try{return await new Promise((resolve,reject)=>{const tx=db.transaction('records','readonly'),store=tx.objectStore('records');let keys,values;store.getAllKeys().onsuccess=event=>keys=event.target.result;store.getAll().onsuccess=event=>values=event.target.result;tx.oncomplete=()=>resolve({keys,values});tx.onabort=reject;});}finally{db.close();}}; 87 const change=async callback=>{const db=await openRaw();try{await new Promise((resolve,reject)=>{const tx=db.transaction('records','readwrite');callback(tx.objectStore('records'));tx.oncomplete=resolve;tx.onabort=reject;});}finally{db.close();}}; 88 const bytes=value=>Array.from(new Uint8Array(value)); 89 const before=await readRows(),coordinateIndex=before.keys.findIndex(key=>JSON.stringify(bytes(key))===JSON.stringify(coordinate)); 90 check(coordinateIndex>=0); 91 const prefixInput=new Uint8Array([...new TextEncoder().encode('radroots.browser.local_outbox.operation.prefix.v2\0'),...new Uint8Array(32).fill(244)]); 92 const prefix=Array.from(new Uint8Array(await crypto.subtle.digest('SHA-256',prefixInput)).slice(0,16)); 93 const at=kind=>before.keys.findIndex(key=>{const raw=bytes(key);return raw[16]===kind&&JSON.stringify(raw.slice(0,16))===JSON.stringify(prefix);}); 94 const claim=at(3),evidence=at(4),installed=at(10),work=at(11); 95 check([claim,evidence,installed,work].every(index=>index>=0)); 96 await reopened.close(); 97 const faults=[... [coordinateIndex,claim,evidence,installed,work].map(index=>({index})),{index:installed,replacement:work},{index:work,replacement:installed},{index:coordinateIndex,flip:true,fresh:true},{index:claim,move:true}]; 98 for(const fault of faults){ 99 phase='public corruption '+JSON.stringify(fault); 100 const key=before.keys[fault.index];let moved; 101 await change(store=>{ 102 if(fault.move){moved=new Uint8Array(key).slice();moved[17]=0;store.delete(key);store.put(before.values[fault.index],moved.buffer);} 103 else if(fault.flip){const value=new Uint8Array(before.values[fault.index]).slice();value[value.length-1]^=1;store.put(value.buffer,key);} 104 else if(fault.replacement!==undefined)store.put(before.values[fault.replacement],key); 105 else store.delete(key); 106 }); 107 const corrupted=await readRows(); 108 reopened=await WorkspaceFixture.open(245,fingerprint,selection,proof);reopened.set_time(fault.fresh?1000:1500); 109 await refuses(()=>fault.fresh?reopened.admit_public(245):reopened.public_snapshot(244),'recovery_required'); 110 await reopened.close(); 111 const unchanged=await readRows(); 112 check(JSON.stringify(unchanged.keys.map(bytes))===JSON.stringify(corrupted.keys.map(bytes))); 113 check(JSON.stringify(unchanged.values.map(bytes))===JSON.stringify(corrupted.values.map(bytes))); 114 phase+=' restore'; 115 await change(store=>{if(moved)store.delete(moved.buffer);store.put(before.values[fault.index],key);}); 116 reopened=await WorkspaceFixture.open(245,fingerprint,selection,proof);reopened.set_time(1500); 117 check(await reopened.public_snapshot(244)===originalSnapshot);await reopened.close(); 118 } 119 reopened=await WorkspaceFixture.open(245,fingerprint,selection,proof);reopened.set_time(1500); 120 tests.push('actual protected public predecessor deletion, cross-family replacement, corrupt coordinate and wrong-target records refuse without rewriting evidence'); 121 phase='expiry and revocation'; 122 reopened.set_time(2000); 123 await refuses(() => reopened.authenticate(), 'grant_expired'); 124 reopened.set_time(1500); 125 await reopened.revoke(); 126 await reopened.close(); 127 await refuses(() => WorkspaceFixture.open(245, fingerprint, selection, proof), 'grant_revoked'); 128 const capture = await WorkspaceFixture.open_capture(245, fingerprint, selection, proof); 129 await refuses(() => capture.authenticate(), 'unauthorized'); 130 await capture.close(); 131 tests.push('expiry and persisted revocation refuse normal reopen and access'); 132 const buyer = await WorkspaceFixture.create(246); 133 check(!await buyer.is_seller()); 134 check(await buyer.authenticate() === 1); 135 await buyer.close(); 136 tests.push('independent buyer enrollment retains buyer scope'); 137 return tests; 138 } catch(error) { throw Error(phase+': '+String(error)); } 139 } 140 const source = `import init, * as fixture from '/fixture.js'; import previousInit, * as previous from '/before/fixture.js'; 141 const run = ${workflow.toString()}; 142 self.onmessage = async () => { try { await init(); await previousInit(); self.postMessage({tests:await run(fixture, previous)}); } 143 catch(error) { self.postMessage({error:String(error)}); } };`; 144 const server = createServer(async (req,res) => { 145 try { 146 const name = new URL(req.url,'http://localhost').pathname; 147 if (name === '/') { res.setHeader('content-type','text/html'); res.end('<!doctype html><title>Protected seller outbox</title>'); return; } 148 if (name === '/worker.mjs') { res.setHeader('content-type','text/javascript'); res.end(source); return; } 149 const selectedRoot = name.startsWith('/before/') ? previousRoot : root; 150 const path = resolve(selectedRoot, '.' + (name.startsWith('/before/') ? name.slice(7) : name)); 151 assert(path.startsWith(selectedRoot + sep)); 152 res.setHeader('content-type',path.endsWith('.wasm')?'application/wasm':'text/javascript'); 153 res.end(await readFile(path)); 154 } catch { res.writeHead(404); res.end(); } 155 }); 156 await new Promise(done => server.listen(0,'127.0.0.1',done)); 157 const browser = await playwright[engine].launch({headless:true}); 158 const watchdog = setTimeout(() => { void browser.close(); },180_000); 159 watchdog.unref(); 160 const results = []; 161 try { 162 for (const contextName of ['page','worker']) { 163 const context = await browser.newContext(); 164 try { 165 const page = await context.newPage(); 166 page.setDefaultTimeout(60_000); 167 await page.goto(`http://127.0.0.1:${server.address().port}`); 168 const tests = contextName === 'page' 169 ? await page.evaluate(async code => { const fixture = await import('/fixture.js'); await fixture.default(); const previous = await import('/before/fixture.js'); await previous.default(); return await (0,eval)(`(${code})`)(fixture,previous); },workflow.toString()) 170 : await page.evaluate(() => new Promise((done,fail) => { const worker = new Worker('/worker.mjs',{type:'module'}); const timer = setTimeout(() => { worker.terminate(); fail(Error('worker timeout')); },60_000); worker.onmessage = event => { clearTimeout(timer); worker.terminate(); event.data.error ? fail(Error(event.data.error)) : done(event.data.tests); }; worker.onerror = error => { clearTimeout(timer); worker.terminate(); fail(Error(error.message)); }; worker.postMessage({run:true}); })); 171 assert.equal(tests.length,6); 172 results.push({context:contextName,tests}); 173 console.error(JSON.stringify({engine,context:contextName,passed:tests.length})); 174 } finally { await context.close(); } 175 } 176 console.log(JSON.stringify({engine,version:browser.version(),results})); 177 } finally { clearTimeout(watchdog); await browser.close(); await new Promise(done => server.close(done)); }