新增 Chrome 下载接管扩展与 C++ 本地通信组件

实现链接右键发送、手动地址输入和默认关闭的可选 GET 自动接管,支持站点与文件类型过滤。通过 Native Messaging 和当前用户命名管道在任务入库后确认接管,失败恢复浏览器下载并持久化交接状态。保存请求编号、Referer 与 User-Agent,补充本地注册入口、集成包说明及扩展/stdio/IPC/HTTP 回归测试。
This commit is contained in:
tongtong committed 2026-11-16 15:44:44 +08:00
1 parent 6c810c3b4f
commit 028fec64be
41 files changed
+1081 -18

No files matched your search

+48
View File
@@ -0,0 +1,48 @@
#include "../shared/protocol.h"
#include "../shared/pipe.h"
#include <sstream>
#include <iostream>
#include <stdexcept>
#include <chrono>
using namespace browser_bridge;
static void Check(bool ok,const char* text) { if (!ok) throw std::runtime_error(text); }
int main() {
try {
Message fields; std::string error;
Check(Parse(R"({"action":"add","request_id":"abc-1","method":"GET","url":"https://example.test/中文.zip","filename":"\ud83d\ude80.zip"})",fields,error) && Validate(fields,error),"parse UTF-8 and surrogate pair");
Message restored; Check(Parse(Serialize(fields),restored,error) && fields==restored,"JSON roundtrip");
for (const std::string& invalid : {R"({"x":"1","x":"2"})",R"({"x":1})",R"({"x":"\ud800"})",R"({"x":{}})",R"({"x":"a"} trailing)"}) Check(!Parse(invalid,restored,error),"reject malformed flat protocol");
auto invalid=fields; invalid["user_agent"]="test\r\nInjected: yes"; Check(!Validate(invalid,error),"reject header injection");
invalid=fields; invalid["method"]="POST"; Check(!Validate(invalid,error),"reject POST");
std::stringstream framed; Check(WriteFrame(framed,Serialize(fields)),"write native frame");
std::string json; Check(ReadFrame(framed,json) && json==Serialize(fields),"read native frame");
std::stringstream truncated(std::string("\xff\xff\xff\x7f",4)); Check(!ReadFrame(truncated,json),"bound frame allocation");
std::stringstream partial(std::string("\x05\0\0\0ab",6)); Check(!ReadFrame(partial,json),"reject truncated frame");
PipeServer server; auto name=PipeName()+L".Test."+std::to_wstring(GetCurrentProcessId());
server.Start([](const std::string& json,HANDLE) {
Message message; std::string error;
if (!Parse(json,message,error) || !Validate(message,error)) return Serialize(Reply("invalid_request",error));
return Serialize(Reply(Get(message,"action")=="ping"?"ready":"accepted","已接收",Get(message,"request_id"),"42"));
},name);
Message ping{{"action","ping"},{"request_id","ping-1"}};
bool ready=false;
for (int i=0;i<50;++i) {
auto response=Exchange(Serialize(ping),name);
Check(Parse(response,restored,error),"pipe reply JSON");
if (Get(restored,"status")=="ready") { ready=true; break; } Sleep(20);
}
Check(ready,"private per-user named pipe handshake");
auto response=Exchange(Serialize(fields),name); Check(Parse(response,restored,error) && Get(restored,"status")=="accepted" && Get(restored,"task_id")=="42","native IPC request/ack including Unicode");
// A stalled peer must not keep shutdown blocked in a read operation.
HANDLE peer=INVALID_HANDLE_VALUE;
for (int i=0;i<50 && peer==INVALID_HANDLE_VALUE;++i) {
peer=CreateFileW(name.c_str(),GENERIC_READ|GENERIC_WRITE,0,nullptr,OPEN_EXISTING,0,nullptr);
if (peer==INVALID_HANDLE_VALUE) Sleep(20);
}
Check(peer!=INVALID_HANDLE_VALUE,"connect stalled peer");
auto start=std::chrono::steady_clock::now(); server.Stop(); CloseHandle(peer);
Check(std::chrono::steady_clock::now()-start<std::chrono::seconds(2),"stop cancels pending pipe I/O");
std::cout<<"PASS: native framing, UTF-8, protocol bounds, request validation, named-pipe IPC and shutdown\n";
return 0;
} catch (const std::exception& error) { std::cerr<<"FAIL: "<<error.what()<<"\n"; return 1; }
}
@@ -0,0 +1,24 @@
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup Label="ProjectConfigurations">
<ProjectConfiguration Include="Debug|x64"><Configuration>Debug</Configuration><Platform>x64</Platform></ProjectConfiguration>
<ProjectConfiguration Include="Release|x64"><Configuration>Release</Configuration><Platform>x64</Platform></ProjectConfiguration>
</ItemGroup>
<PropertyGroup Label="Globals"><ProjectGuid>{DD6207AB-5434-4613-9173-4DB0FD5DF97C}</ProjectGuid><VcpkgEnabled>false</VcpkgEnabled></PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
<PropertyGroup Label="Configuration"><ConfigurationType>Application</ConfigurationType><PlatformToolset>v143</PlatformToolset><CharacterSet>Unicode</CharacterSet></PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
<PropertyGroup><OutDir>$(ProjectDir)..\..\client\bin\tests\$(Configuration)\</OutDir><IntDir>$(ProjectDir)obj\$(Configuration)\</IntDir><TargetName>browser_bridge_tests</TargetName></PropertyGroup>
<ItemDefinitionGroup>
<ClCompile>
<LanguageStandard>stdcpp20</LanguageStandard><AdditionalOptions>/utf-8 %(AdditionalOptions)</AdditionalOptions><ExceptionHandling>Sync</ExceptionHandling>
<PreprocessorDefinitions>NOMINMAX;UNICODE;_UNICODE;_WIN32_WINNT=0x0601;WINVER=0x0601;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<RuntimeLibrary Condition="'$(Configuration)'=='Debug'">MultiThreadedDebug</RuntimeLibrary>
<RuntimeLibrary Condition="'$(Configuration)'=='Release'">MultiThreaded</RuntimeLibrary>
</ClCompile>
<Link><SubSystem>Console</SubSystem><MinimumRequiredVersion>6.01</MinimumRequiredVersion></Link>
</ItemDefinitionGroup>
<ItemGroup><ClCompile Include="bridge_tests.cpp" /><ClCompile Include="..\shared\protocol.cpp" /><ClCompile Include="..\shared\pipe.cpp" /></ItemGroup>
<ItemGroup><ClInclude Include="..\shared\protocol.h" /><ClInclude Include="..\shared\pipe.h" /><ClInclude Include="..\shared\identity.h" /></ItemGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
</Project>
+121
View File
@@ -0,0 +1,121 @@
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');
});
+20
View File
@@ -0,0 +1,20 @@
import json, pathlib, re, struct, subprocess, sys
root = pathlib.Path(__file__).resolve().parents[2]
origin = re.search(r'kExtensionOrigin\[\]="([^"]+)"', (root/'browser/shared/identity.h').read_text()).group(1)
def frame(value):
raw=json.dumps(value,ensure_ascii=False).encode('utf-8')
return struct.pack('<I',len(raw))+raw
# Invalid requests never reach the real desktop or touch user tasks.
requests=[{'action':'add','request_id':'bad-1','method':'POST','url':'https://example.test/file'}, {'action':'add','request_id':'bad-2','method':'GET','url':'file:///C:/secret'}, {'action':'ping','request_id':123}]
result=subprocess.run([sys.argv[1],origin],input=b''.join(map(frame,requests)),capture_output=True,timeout=10)
assert result.returncode==0, result.stderr
raw=result.stdout
for request in requests:
assert len(raw)>=4
length=struct.unpack('<I',raw[:4])[0]
response=json.loads(raw[4:4+length]); raw=raw[4+length:]
assert response['status']=='invalid_request',response
assert raw==b'', 'stdout must contain only framed JSON'
wrong=subprocess.run([sys.argv[1],'chrome-extension://wrong/'],input=frame({'action':'ping','request_id':'test'}),capture_output=True,timeout=5)
assert wrong.returncode!=0 and not wrong.stdout
print('PASS: compiled Native Messaging Host framing and extension-origin validation')