import test from 'node:test'; import assert from 'node:assert/strict'; import fs from 'node:fs'; import crypto from 'node:crypto'; import {DEFAULTS, eligible, httpUrl, linkReferrer, handoff, recover} from '../chrome/logic.mjs'; const request = {action:'add', request_id:'test-1', method:'GET', url:'https://example.com/file.zip', referrer:'', filename:'file.zip', user_agent:'test'}; function mock() { const item = {id:1, url:request.url, finalUrl:request.url, state:'in_progress', paused:false, danger:'safe'}; const data = {}, events = []; const api = {storage:{local:{ async get(key) { return key === null ? structuredClone(data) : {[key]: structuredClone(data[key])}; }, async set(values) { Object.assign(data, structuredClone(values)); }, async remove(key) { delete data[key]; } }}, downloads:{ async search() { return [structuredClone(item)]; }, async pause() { events.push('pause'); item.paused=true; }, async resume() { events.push('resume'); item.paused=false; }, async cancel() { events.push('cancel'); item.state='interrupted'; item.paused=false; } }}; return {api,item,data,events}; } test('extension identity matches the native host allowlist', () => { const manifest = JSON.parse(fs.readFileSync(new URL('../chrome/manifest.json', import.meta.url))); const id = [...crypto.createHash('sha256').update(Buffer.from(manifest.key,'base64')).digest().subarray(0,16)].map(v=>String.fromCharCode(97+(v>>4),97+(v&15))).join(''); assert.ok(fs.readFileSync(new URL('../shared/identity.h',import.meta.url),'utf8').includes(`chrome-extension://${id}/`)); assert.equal(DEFAULTS.auto,false); }); test('auto capture requires observed GET and honors site/type filters', () => { const {item} = mock(); const observed = {method:'GET',time:Date.now()}; assert.equal(eligible(item,DEFAULTS,observed),false); const config={auto:true,sites:'example.com',extensions:'.zip'}; assert.equal(eligible(item,config,observed),true); assert.equal(eligible(item,config,{...observed,method:'POST'}),false); assert.equal(eligible(item,config,null),false); assert.equal(eligible({...item,paused:true},config,observed),false); assert.equal(eligible({...item,danger:'url'},config,observed),false); assert.equal(eligible(item,{...config,sites:'other.example'},observed),false); assert.equal(eligible(item,{...config,extensions:'.mp4'},observed),false); assert.equal(httpUrl('blob:https://example.com/file'),''); assert.equal(httpUrl('https://user:password@example.com/file'),''); }); test('cancel browser only after desktop persisted acknowledgement', async () => { const m=mock(); const result=await handoff(m.api,m.item,request,async r=>{assert.equal(m.item.paused,true); assert.equal(m.data.pending_1.phase,'sending'); m.events.push('ack'); return {status:'accepted',request_id:r.request_id,task_id:'42'};}); assert.equal(result.status,'accepted'); assert.deepEqual(m.events,['pause','ack','cancel']); assert.equal(m.data.pending_1,undefined); }); test('offline desktop and duplicate restore the original browser download', async () => { for (const status of ['client_not_running','duplicate']) { const m=mock(); const result=await handoff(m.api,m.item,request,async()=>({status,message:status})); assert.equal(result.status,'fallback'); assert.deepEqual(m.events,['pause','resume']); assert.equal(m.item.paused,false); } }); test('mismatched acknowledgement never cancels the browser', async () => { const m=mock(); await handoff(m.api,m.item,request,async()=>({status:'accepted',request_id:'wrong',task_id:'42'})); assert.deepEqual(m.events,['pause','resume']); }); test('native disconnect restores browser', async () => { const m=mock(); await handoff(m.api,m.item,request,async()=>{throw new Error('host lost');}); assert.deepEqual(m.events,['pause','resume']); }); test('cancel failure is journaled and recovery retries without resubmitting', async () => { const m=mock(); const cancel=m.api.downloads.cancel; m.api.downloads.cancel=async()=>{throw new Error('busy');}; assert.equal((await handoff(m.api,m.item,request,async r=>({status:'accepted',request_id:r.request_id,task_id:'42'}))).status,'recovery_pending'); assert.equal(m.data.pending_1.phase,'cancel'); m.api.downloads.cancel=cancel; await recover(m.api,async()=>assert.fail('must not resubmit accepted task'),false); assert.equal(m.item.state,'interrupted'); assert.equal(m.data.pending_1,undefined); }); test('resume failure survives worker restart and can be recovered', async () => { const m=mock(); const resume=m.api.downloads.resume; m.api.downloads.resume=async()=>{throw new Error('busy');}; await handoff(m.api,m.item,request,async()=>{throw new Error('offline');}); assert.equal(m.data.pending_1.phase,'resume'); m.api.downloads.resume=resume; await recover(m.api,async()=>assert.fail('must resume without native retry'),false); assert.equal(m.item.paused,false); assert.equal(m.data.pending_1,undefined); }); test('worker restart retries the same request id; disabling auto restores browser', async () => { for (const auto of [true,false]) { const m=mock(); m.item.paused=true; m.data.pending_1={id:1,request,phase:'sending',created:Date.now(),original:request.url}; await recover(m.api,async r=>{assert.equal(r.request_id,'test-1'); return {status:'accepted',request_id:r.request_id,task_id:'42'};},auto); assert.equal(m.item.state,auto?'interrupted':'in_progress'); assert.equal(m.item.paused,false); } }); test('background worker wires observed GET to native acknowledgement before cancel', async () => { const m=mock(); m.data.config={auto:true,sites:'example.com',extensions:'.zip'}; function event() { return {listeners:[], addListener(fn){this.listeners.push(fn);}, removeListener(fn){this.listeners=this.listeners.filter(x=>x!==fn);}, hasListener(fn){return this.listeners.includes(fn);}, async emit(...args){for(const fn of [...this.listeners]) await fn(...args);}}; } const old=globalThis.chrome; const api={...m.api, runtime:{id:'test-extension',getURL:()=> 'chrome-extension://test-extension/',onInstalled:event(),onStartup:event(),onMessage:event(), connectNative(name){assert.equal(name,'com.ttstd.ttdownloader'); const port={onMessage:event(),onDisconnect:event(),disconnect(){},postMessage(r){m.events.push('ack');queueMicrotask(()=>port.onMessage.emit({status:'accepted',request_id:r.request_id,task_id:'42',message:'accepted'}));}}; return port;}}, contextMenus:{onClicked:event()},alarms:{onAlarm:event(),create(){}},permissions:{onAdded:event(),onRemoved:event(),async contains(){return true;}}, webRequest:{onBeforeRequest:event()},action:{async setBadgeText(){},async setBadgeBackgroundColor(){},async setTitle(){}},notifications:{create(_,callback){callback();}}}; api.storage.onChanged=event(); api.downloads.onCreated=event(); globalThis.chrome=api; try { await import('../chrome/background.js'); await new Promise(resolve=>setTimeout(resolve,10)); await api.webRequest.onBeforeRequest.emit({url:request.url,method:'GET'}); await api.downloads.onCreated.emit(m.item); assert.deepEqual(m.events,['pause','ack','cancel']); assert.equal(m.data.lastResult.status,'accepted'); } finally { globalThis.chrome=old; } }); test('zero task id is not an acknowledgement', async () => { const m=mock(); await handoff(m.api,m.item,request,async()=>({status:'accepted',request_id:request.request_id,task_id:'0'})); assert.deepEqual(m.events,['pause','resume']); }); test('restart never pauses a sending task that the user resumed', async () => { const m=mock(); m.data.pending_1={id:1,request,phase:'sending',created:Date.now(),original:request.url}; await recover(m.api,async()=>assert.fail('do not resend'),true); assert.equal(m.item.paused,false); assert.deepEqual(m.events,[]); }); test('storage failure during fallback must not strand a paused download', async () => { const m=mock(); const set=m.api.storage.local.set; m.api.storage.local.set=async values=>{if(values.pending_1?.phase==='resume') throw new Error('quota'); return set(values);}; await handoff(m.api,m.item,request,async()=>{throw new Error('offline');}); assert.equal(m.item.paused,false); }); test('manual cross-site handoff does not leak source query parameters', () => { assert.equal(linkReferrer('https://source.test/page?secret=value','https://download.test/file'),'https://source.test/'); assert.equal(linkReferrer('https://source.test/page?secret=value','http://download.test/file'),''); assert.equal(linkReferrer('https://source.test/page#fragment','https://source.test/file'),'https://source.test/page'); });