Add browser download confirmation and parameterized client startup
This commit is contained in:
1 parent
028fec64be
commit
3cf197a98c
25 files changed
+568
-46
No files matched your search
+24
-4
@@ -15,14 +15,34 @@ Edge:在 `edge://extensions` 加载同一目录,并执行 `client/bin/ttdown
|
||||
|
||||
## 使用方式
|
||||
|
||||
- 右键点击 HTTP/HTTPS 链接,选择“使用 TTDownloader 下载”。
|
||||
- 在扩展弹窗粘贴下载地址后发送。客户端接收并入库后显示成功;重复会明确显示已有任务。
|
||||
- 右键点击 HTTP/HTTPS 链接,选择“使用 TTDownloader 下载”,或在扩展弹窗粘贴地址后发送。客户端会打开“添加下载任务”窗口并预填地址,选择保存目录后点击“添加任务”才开始下载;捕获地址绑定本次请求,地址框只读。已有任务会明确提示重复。
|
||||
- 发送地址时客户端未运行,Native Host 会启动与其同目录的 `ttdownloader.exe`,最多等待 10 秒就绪,再打开添加窗口。Debug Host 对应 `ttdownloader_d.exe`。必须保留软件包中的目录结构;启动失败会显示具体错误。
|
||||
- 默认不自动接管。勾选“自动接管”,保存时按 Chrome 提示授予可选站点访问与 webRequest 权限。可指定站点和文件类型;留空表示不限制。
|
||||
- 站点以空格或逗号分隔,支持 `example.com` 精确匹配和 `*.example.com` 子域匹配。文件类型如 `.zip,.exe,.mp4`,按文件名或 URL 路径后缀匹配。
|
||||
|
||||
自动接管先将恢复记录写入扩展本地存储,再暂停浏览器下载。桌面任务入库确认后才取消浏览器下载。通信失败、客户端未启动或重复任务会保留/恢复浏览器下载。失败会显示通知、工具栏 `!` 和弹窗状态。后台重启时重用同一个请求编号,避免重复创建桌面任务;已恢复的浏览器任务不会再次被暂停。
|
||||
自动接管先将恢复记录写入扩展本地存储,再暂停浏览器下载并打开客户端添加窗口。等待确认时显示 `…`,不会取消浏览器下载;确认入库后才取消。关闭添加窗口、两分钟未确认、关闭自动接管或通信失败时恢复浏览器。扩展后台重启会查询同一个请求编号,避免重开窗口或重复创建任务;已恢复的浏览器任务不会再次被暂停。用户确认与取消等待同时发生时,以引擎已入库的结果为准。
|
||||
|
||||
桌面客户端需已启动,首版不自动启动客户端。入库确认代表任务已交给桌面引擎,并不代表目标服务器已经返回下载内容。
|
||||
“检查桌面连接”只检查状态,不启动客户端;查询和取消等待也不启动客户端。入库确认代表任务已交给桌面引擎,并不代表目标服务器已经返回下载内容。更新后请完全退出旧客户端再打开新版,并在扩展管理页面重新加载扩展。
|
||||
|
||||
### 已运行却无法连接
|
||||
|
||||
如果提示“客户端已运行,但浏览器接口未就绪”,先从托盘完全退出旧版,再启动本次软件包的 `client/bin/ttdownloader.exe`。单实例机制会把第二次启动转交给旧进程,仅再次双击新版不能替换正在运行的旧进程。旧版不包含浏览器通信接口。
|
||||
|
||||
“本地组件未连接”表示 Host 注册、路径或扩展来源有问题:运行当前软件包的 `browser/register-host.cmd`;移动目录后也须重新注册。“未找到当前用户会话的客户端”表示当前用户和会话中没有可连接的桌面实例。请让浏览器和客户端在同一用户、同一登录会话下运行。
|
||||
|
||||
## 命令行启动
|
||||
|
||||
```cmd
|
||||
ttdownloader.exe --add "https://example.com/file.zip?a=1&b=2"
|
||||
ttdownloader.exe "https://example.com/file.zip"
|
||||
ttdownloader.exe --add
|
||||
```
|
||||
|
||||
带地址时打开并预填添加窗口,`--add` 单独使用打开添加窗口;不带参数正常启动主窗口。用户点击“添加任务”前不会创建下载任务。地址包含 `&` 等字符时请始终用双引号包住。
|
||||
|
||||
客户端已运行时,新进程通过有大小限制的 `WM_COPYDATA` 把启动请求交给现有实例后退出;启动中的窗口会等待短时间就绪。已有未处理的添加窗口时明确提示,不覆盖输入。参数无效、实例版本过旧或权限不一致时明确报错。
|
||||
|
||||
Chrome 冷启动使用内部参数 `--browser-request` 传递经过校验的完整请求,保留 request_id、Referer、User-Agent 和文件名提示。Host 直接调用 `CreateProcessW` 并对每个参数执行 Windows argv 转义,不经过命令行 shell;冷启动和后续管道查询沿用同一请求编号。
|
||||
|
||||
## 支持范围
|
||||
|
||||
|
||||
@@ -1,15 +1,20 @@
|
||||
import {DEFAULTS, httpUrl, eligible, linkReferrer, requestFor, handoff, recover} from './logic.mjs';
|
||||
const HOST = 'com.ttstd.ttdownloader';
|
||||
const observed = new Map(), busy = new Set();
|
||||
let recovery = null;
|
||||
let recovery = null, pollTimer = null;
|
||||
function pollConfirmation() {
|
||||
if (pollTimer) return;
|
||||
pollTimer = setTimeout(() => { pollTimer = null; restorePending(); }, 1500);
|
||||
}
|
||||
const config = async () => ({...DEFAULTS, ...(await chrome.storage.local.get('config')).config});
|
||||
async function status(result) {
|
||||
await chrome.storage.local.set({lastResult: {...result, time: Date.now()}});
|
||||
const waiting = result.status === 'awaiting_confirmation';
|
||||
const ok = ['accepted', 'ready'].includes(result.status);
|
||||
await chrome.action.setBadgeText({text: ok ? 'OK' : '!'});
|
||||
await chrome.action.setBadgeText({text: waiting ? '…' : ok ? 'OK' : '!'});
|
||||
await chrome.action.setBadgeBackgroundColor({color: ok ? '#247a48' : '#af4d00'});
|
||||
await chrome.action.setTitle({title: 'TTDownloader:' + result.message});
|
||||
if (!ok && result.status !== 'duplicate') chrome.notifications.create({type: 'basic', iconUrl: 'icon.png', title: 'TTDownloader 下载接管', message: result.message}, () => { void chrome.runtime.lastError; });
|
||||
if (!ok && !waiting && result.status !== 'duplicate') chrome.notifications.create({type: 'basic', iconUrl: 'icon.png', title: 'TTDownloader 下载接管', message: result.message}, () => { void chrome.runtime.lastError; });
|
||||
return result;
|
||||
}
|
||||
function native(request) {
|
||||
@@ -43,7 +48,12 @@ async function configure() {
|
||||
}
|
||||
async function restorePending() {
|
||||
if (recovery || busy.size) return recovery;
|
||||
recovery = (async () => { for (const outcome of await recover(chrome, native, (await config()).auto)) await status(outcome); })()
|
||||
recovery = (async () => {
|
||||
for (const outcome of await recover(chrome, native, (await config()).auto)) {
|
||||
await status(outcome);
|
||||
if (outcome.status === 'awaiting_confirmation') pollConfirmation();
|
||||
}
|
||||
})()
|
||||
.catch(error => status({status: 'error', message: '恢复下载状态失败:' + error.message})).finally(() => { recovery = null; });
|
||||
return recovery;
|
||||
}
|
||||
@@ -55,7 +65,10 @@ chrome.runtime.onStartup.addListener(() => { configure().catch(console.error); r
|
||||
chrome.alarms.onAlarm.addListener(alarm => { if (alarm.name === 'recover') restorePending(); });
|
||||
chrome.permissions.onAdded.addListener(() => configure().catch(console.error));
|
||||
chrome.permissions.onRemoved.addListener(() => configure().catch(console.error));
|
||||
chrome.storage.onChanged.addListener(changes => { if (changes.config) { configure().catch(console.error); restorePending(); } });
|
||||
chrome.storage.onChanged.addListener(changes => {
|
||||
if (changes.config) { configure().catch(console.error); restorePending(); }
|
||||
if (Object.entries(changes).some(([key, change]) => key.startsWith('pending_') && change.newValue?.phase === 'confirming')) pollConfirmation();
|
||||
});
|
||||
chrome.contextMenus.onClicked.addListener(async info => {
|
||||
if (info.menuItemId !== 'send') return;
|
||||
try { await status(await native(requestFor(info.linkUrl, linkReferrer(info.pageUrl, info.linkUrl)))); }
|
||||
@@ -68,7 +81,7 @@ chrome.downloads.onCreated.addListener(async item => {
|
||||
busy.add(item.id);
|
||||
try { await status(await handoff(chrome, item, requestFor(url, item.referrer, item.filename || ''), native)); }
|
||||
catch (error) { await status({status: 'error', message: '接管失败,请在下载页检查任务:' + error.message}); }
|
||||
finally { busy.delete(item.id); }
|
||||
finally { busy.delete(item.id); pollConfirmation(); }
|
||||
});
|
||||
chrome.runtime.onMessage.addListener((message, sender, respond) => {
|
||||
if (sender.id !== chrome.runtime.id || !sender.url?.startsWith(chrome.runtime.getURL(''))) return;
|
||||
|
||||
@@ -21,7 +21,7 @@ export function linkReferrer(source, target) {
|
||||
}
|
||||
export function requestFor(url, referrer = '', filename = '') {
|
||||
const normalized = httpUrl(url); if (!normalized) throw new Error('仅支持不含账号密码的 HTTP/HTTPS 下载地址');
|
||||
return {action: 'add', request_id: crypto.randomUUID(), method: 'GET', url: normalized,
|
||||
return {action: 'add', confirmation: 'required', request_id: crypto.randomUUID(), method: 'GET', url: normalized,
|
||||
referrer: httpUrl(referrer), filename: filename.split(/[\\/]/).pop().slice(0, 240), user_agent: navigator.userAgent};
|
||||
}
|
||||
const key = id => `pending_${id}`;
|
||||
@@ -54,6 +54,23 @@ async function finish(api, record) {
|
||||
return {status: 'recovery_pending', message: '桌面已接收任务,浏览器取消失败,将继续重试'};
|
||||
}
|
||||
}
|
||||
const acknowledged = (reply, request) => reply?.status === 'accepted' && reply.request_id === request.request_id
|
||||
&& typeof reply.task_id === 'string' && /^[1-9][0-9]{0,18}$/.test(reply.task_id);
|
||||
async function abandon(api, record, sendNative) {
|
||||
try {
|
||||
const reply = await sendNative({action: 'cancel', request_id: record.request.request_id});
|
||||
if (acknowledged(reply, record.request)) {
|
||||
record.phase = 'cancel'; record.task_id = reply.task_id;
|
||||
try { await save(api, record); } catch {} // The existing request journal still permits an idempotent retry.
|
||||
return finish(api, record);
|
||||
}
|
||||
if (reply?.status === 'awaiting_confirmation' && reply.request_id === record.request.request_id) {
|
||||
record.phase = 'confirming'; try { await save(api, record); } catch {}
|
||||
return {status: 'awaiting_confirmation', message: reply.message};
|
||||
}
|
||||
} catch {} // If the client disappeared, preserve the browser's original download.
|
||||
return restore(api, record, '接管未完成,请检查客户端添加窗口');
|
||||
}
|
||||
export async function handoff(api, item, request, sendNative, saved = null) {
|
||||
const record = saved || {id: item.id, request, phase: 'pause', created: Date.now(), original: httpUrl(item.finalUrl || item.url)};
|
||||
if (record.phase === 'cancel') return finish(api, record);
|
||||
@@ -62,13 +79,21 @@ export async function handoff(api, item, request, sendNative, saved = null) {
|
||||
// Journal intent before pausing, so a service-worker restart cannot strand a paused task.
|
||||
await save(api, record);
|
||||
if (!item.paused) await api.downloads.pause(item.id);
|
||||
record.phase = 'sending'; await save(api, record);
|
||||
const reply = await sendNative(record.request);
|
||||
if (reply?.status !== 'accepted' || reply.request_id !== request.request_id || typeof reply.task_id !== 'string' || !/^[1-9][0-9]{0,18}$/.test(reply.task_id))
|
||||
const confirming = record.phase === 'confirming';
|
||||
if (!confirming) record.phase = 'sending';
|
||||
await save(api, record);
|
||||
const reply = await sendNative(confirming ? {action: 'query', request_id: request.request_id} : record.request);
|
||||
if (reply?.status === 'awaiting_confirmation' && reply.request_id === request.request_id) {
|
||||
record.phase = 'confirming'; await save(api, record);
|
||||
return {status: 'awaiting_confirmation', message: reply.message || '请在客户端确认添加任务;取消后将恢复浏览器下载'};
|
||||
}
|
||||
if (!acknowledged(reply, request))
|
||||
return restore(api, record, reply?.message || '桌面未确认接管');
|
||||
record.phase = 'cancel'; record.task_id = reply.task_id; await save(api, record);
|
||||
record.phase = 'cancel'; record.task_id = reply.task_id;
|
||||
try { await save(api, record); } catch {}
|
||||
return finish(api, record);
|
||||
} catch (error) {
|
||||
if (record.phase === 'sending' || record.phase === 'confirming') return abandon(api, record, sendNative);
|
||||
return restore(api, record, error.message || '本地通信失败,结果未确认');
|
||||
}
|
||||
}
|
||||
@@ -76,9 +101,16 @@ export async function recover(api, sendNative, auto) {
|
||||
const values = await api.storage.local.get(null), outcomes = [];
|
||||
for (const record of Object.values(values).filter(v => v && v.request && Number.isInteger(v.id) && v.phase)) {
|
||||
const item = await current(api, record.id);
|
||||
if (!item || httpUrl(item.finalUrl || item.url) !== record.original || item.state !== 'in_progress') { await remove(api, record.id); continue; }
|
||||
if (record.phase === 'sending' && !item.paused) {
|
||||
await remove(api, record.id); outcomes.push({status: 'warning', message: '浏览器下载已恢复,已停止重复接管;请核对桌面任务列表'}); continue;
|
||||
if (!item || httpUrl(item.finalUrl || item.url) !== record.original || item.state !== 'in_progress') {
|
||||
if (record.phase === 'confirming' || record.phase === 'sending') outcomes.push(await abandon(api, record, sendNative));
|
||||
else await remove(api, record.id);
|
||||
continue;
|
||||
}
|
||||
if (record.phase === 'confirming' && (!item.paused || !auto || Date.now() - record.created > 120000)) {
|
||||
outcomes.push(await abandon(api, record, sendNative)); continue;
|
||||
}
|
||||
if (record.phase === 'sending' && (!item.paused || !auto || Date.now() - record.created > 120000)) {
|
||||
outcomes.push(await abandon(api, record, sendNative)); continue;
|
||||
}
|
||||
if (record.phase === 'cancel') outcomes.push(await finish(api, record));
|
||||
else if (!auto || Date.now() - record.created > 120000 || record.phase === 'resume') outcomes.push(await restore(api, record, '接管未完成'));
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
"manifest_version": 3,
|
||||
"name": "TTDownloader 下载接管",
|
||||
"description": "将主动发起的 HTTP/HTTPS 下载交给 TTDownloader,自动接管默认关闭。",
|
||||
"version": "0.1.0",
|
||||
"version": "0.2.0",
|
||||
"minimum_chrome_version": "109",
|
||||
"key": "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAvbbxlyA8oQYALtekWYplS8AuRDPyQmQX51/zpbfYT10Zpsbs+8yd0/l4aP9ByJyjs0N3oI0EsFcA6FPqWK+/SPDeMqZiyxSiIGzcy+zCjYiKelUSzBz80gayXk6R509YV2GKbpt9LOliK92GQy+bacblVScXtqKqmjrubTo+WplRXnPjS0pv2Kx7saSyX10ajjsOTmg1kNaN3x1tCbkOSXR+46idt5VC78sSvixfqwdD0tIqcH7TI6jN0t3nvQakFgfYlcjAgAJrC1PYZdoZMAT2dOjyXV73Bf2y7NHvRQtkDj37Cm88AOH6FncvME7zUbiGrfmZx+ik+rdBQHUULQIDAQAB",
|
||||
"permissions": [
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
#pragma once
|
||||
#include "../shared/protocol.h"
|
||||
#include <functional>
|
||||
namespace browser_bridge {
|
||||
// Launch only for an explicit add. Queries and connection checks must never start the app.
|
||||
inline std::string ForwardToClient(const Message& request,const std::string& json,
|
||||
const std::function<std::string(const std::string&)>& exchange,
|
||||
const std::function<std::string()>& launch,
|
||||
const std::function<std::string(const std::string&)>& wait_ready) {
|
||||
auto response=exchange(json);
|
||||
Message reply; std::string error;
|
||||
if (Get(request,"action")!="add" || !Parse(response,reply,error)) return response;
|
||||
const auto status=Get(reply,"status");
|
||||
if (status!="client_not_running" && status!="client_not_ready") return response;
|
||||
if (status=="client_not_running") {
|
||||
auto failure=launch(); if (!failure.empty()) return failure;
|
||||
}
|
||||
auto probe=wait_ready(Serialize({{"action","ping"},{"request_id",Get(request,"request_id")}}));
|
||||
if (Parse(probe,reply,error) && Get(reply,"status")=="ready") return exchange(json);
|
||||
return probe;
|
||||
}
|
||||
}
|
||||
+42
-1
@@ -1,6 +1,8 @@
|
||||
#include "../shared/protocol.h"
|
||||
#include "../shared/pipe.h"
|
||||
#include "../shared/identity.h"
|
||||
#include "client_connection.h"
|
||||
#include "../shared/command_line.h"
|
||||
#include <fcntl.h>
|
||||
#include <io.h>
|
||||
#include <iostream>
|
||||
@@ -10,6 +12,45 @@ std::string Utf8(const std::wstring& value) {
|
||||
int size=WideCharToMultiByte(CP_UTF8,0,value.data(),static_cast<int>(value.size()),nullptr,0,nullptr,nullptr);
|
||||
std::string text(size,0); WideCharToMultiByte(CP_UTF8,0,value.data(),static_cast<int>(value.size()),text.data(),size,nullptr,nullptr); return text;
|
||||
}
|
||||
std::string LaunchClient(const browser_bridge::Message& request) {
|
||||
using namespace browser_bridge;
|
||||
// Launch a fixed sibling. Validated browser data is one argv value, never shell code.
|
||||
std::vector<wchar_t> module(32768);
|
||||
DWORD size=GetModuleFileNameW(nullptr,module.data(),static_cast<DWORD>(module.size()));
|
||||
if (!size || size>=module.size()) return Serialize(Reply("launch_failed","无法确定客户端安装目录"));
|
||||
std::wstring path(module.data()); auto slash=path.find_last_of(L"\\/");
|
||||
const auto directory=path.substr(0,slash);
|
||||
const bool debug=path.substr(slash+1)==L"ttdownloader_native_host_d.exe";
|
||||
path=directory+(debug?L"\\ttdownloader_d.exe":L"\\ttdownloader.exe");
|
||||
const auto json=Serialize(request);
|
||||
int length=MultiByteToWideChar(CP_UTF8,MB_ERR_INVALID_CHARS,json.data(),static_cast<int>(json.size()),nullptr,0);
|
||||
if (!length) return Serialize(Reply("launch_failed","启动参数不是有效 UTF-8"));
|
||||
std::wstring payload(length,L'\0');
|
||||
MultiByteToWideChar(CP_UTF8,MB_ERR_INVALID_CHARS,json.data(),static_cast<int>(json.size()),payload.data(),length);
|
||||
std::wstring command=QuoteArgument(path)+L" --browser-request "+QuoteArgument(payload);
|
||||
if (command.size()>=32767) return Serialize(Reply("launch_failed","下载地址和上下文过长,请先手动启动客户端"));
|
||||
STARTUPINFOW startup{sizeof(startup)}; PROCESS_INFORMATION process{};
|
||||
startup.dwFlags=STARTF_USESHOWWINDOW; startup.wShowWindow=SW_SHOWNORMAL;
|
||||
if (!CreateProcessW(path.c_str(),command.data(),nullptr,nullptr,FALSE,0,nullptr,directory.c_str(),&startup,&process))
|
||||
return Serialize(Reply("launch_failed","无法启动 TTDownloader(Windows 错误 "+std::to_string(GetLastError())+"),请检查安装目录"));
|
||||
CloseHandle(process.hThread); CloseHandle(process.hProcess);
|
||||
return {};
|
||||
}
|
||||
std::string WaitForClient(const std::string& ping) {
|
||||
using namespace browser_bridge;
|
||||
Message reply; std::string error;
|
||||
const auto deadline=GetTickCount64()+10000;
|
||||
do {
|
||||
Sleep(100); auto probe=Exchange(ping);
|
||||
if (Parse(probe,reply,error) && Get(reply,"status")=="ready") return probe;
|
||||
if (Get(reply,"status")!="client_not_running" && Get(reply,"status")!="client_not_ready") return probe;
|
||||
} while (GetTickCount64()<deadline);
|
||||
return Serialize(Reply("client_not_ready","客户端未能就绪,请完全退出旧版后启动新版,再发送下载地址"));
|
||||
}
|
||||
std::string SendToClient(const browser_bridge::Message& request,const std::string& json) {
|
||||
return browser_bridge::ForwardToClient(request,json,
|
||||
[](const std::string& value) { return browser_bridge::Exchange(value); },[&] { return LaunchClient(request); },WaitForClient);
|
||||
}
|
||||
int RegisterHost(const std::string& browser,bool remove) {
|
||||
if (browser!="chrome" && browser!="edge" && browser!="both") { std::cerr<<"Expected chrome, edge or both\n"; return 1; }
|
||||
std::vector<wchar_t> executable(32768),local(32768);
|
||||
@@ -57,7 +98,7 @@ int main(int argc,char** argv) {
|
||||
if (!browser_bridge::Parse(json,fields,error) || !browser_bridge::Validate(fields,error))
|
||||
response=browser_bridge::Serialize(browser_bridge::Reply("invalid_request",error,browser_bridge::Get(fields,"request_id")));
|
||||
else {
|
||||
response=browser_bridge::Exchange(json);
|
||||
response=SendToClient(fields,json);
|
||||
browser_bridge::Message reply;
|
||||
const auto expected=browser_bridge::Get(fields,"request_id");
|
||||
if (!browser_bridge::Parse(response,reply,error) || browser_bridge::Get(reply,"status").empty()
|
||||
|
||||
@@ -19,6 +19,6 @@
|
||||
<Link><SubSystem>Console</SubSystem><MinimumRequiredVersion>6.01</MinimumRequiredVersion></Link>
|
||||
</ItemDefinitionGroup>
|
||||
<ItemGroup><ClCompile Include="main.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>
|
||||
<ItemGroup><ClInclude Include="client_connection.h" /><ClInclude Include="..\shared\command_line.h" /><ClInclude Include="..\shared\protocol.h" /><ClInclude Include="..\shared\pipe.h" /><ClInclude Include="..\shared\identity.h" /></ItemGroup>
|
||||
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
|
||||
</Project>
|
||||
@@ -0,0 +1,13 @@
|
||||
#pragma once
|
||||
#include <string>
|
||||
namespace browser_bridge {
|
||||
// Quote one argv value for CommandLineToArgvW/CreateProcessW; no shell is involved.
|
||||
inline std::wstring QuoteArgument(const std::wstring& value) {
|
||||
std::wstring result=L"\""; size_t slashes=0;
|
||||
for (wchar_t c:value) {
|
||||
if (c==L'\\') { ++slashes; continue; }
|
||||
result.append(c==L'"'?slashes*2+1:slashes,L'\\'); slashes=0; result+=c;
|
||||
}
|
||||
result.append(slashes*2,L'\\'); return result+L'"';
|
||||
}
|
||||
}
|
||||
+26
-3
@@ -1,17 +1,19 @@
|
||||
#include "pipe.h"
|
||||
#include "protocol.h"
|
||||
#include <sddl.h>
|
||||
#include <tlhelp32.h>
|
||||
#include <vector>
|
||||
#include <memory>
|
||||
#include <sstream>
|
||||
#include <utility>
|
||||
#pragma comment(lib,"advapi32.lib")
|
||||
#pragma comment(lib,"user32.lib")
|
||||
namespace browser_bridge {
|
||||
namespace {
|
||||
using Handle=std::unique_ptr<void,decltype(&CloseHandle)>;
|
||||
std::wstring UserSid() {
|
||||
std::wstring UserSid(HANDLE process=GetCurrentProcess()) {
|
||||
HANDLE raw=nullptr;
|
||||
if (!OpenProcessToken(GetCurrentProcess(),TOKEN_QUERY,&raw)) return {};
|
||||
if (!OpenProcessToken(process,TOKEN_QUERY,&raw)) return {};
|
||||
Handle token(raw,&CloseHandle); DWORD size=0;
|
||||
GetTokenInformation(token.get(),TokenUser,nullptr,0,&size);
|
||||
std::vector<char> buffer(size);
|
||||
@@ -20,6 +22,23 @@ std::wstring UserSid() {
|
||||
if (!ConvertSidToStringSidW(reinterpret_cast<TOKEN_USER*>(buffer.data())->User.Sid,&sid)) return {};
|
||||
std::wstring result(sid); LocalFree(sid); return result;
|
||||
}
|
||||
bool ClientRunning() {
|
||||
if (FindWindowW(L"TTDownloaderMainWindow",nullptr)) return true;
|
||||
// A minimized/tray client may belong to another desktop. Match both user and session.
|
||||
const auto sid=UserSid(); DWORD session=0;
|
||||
if (sid.empty() || !ProcessIdToSessionId(GetCurrentProcessId(),&session)) return false;
|
||||
Handle snapshot(CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS,0),&CloseHandle);
|
||||
if (snapshot.get()==INVALID_HANDLE_VALUE) { snapshot.release(); return false; }
|
||||
PROCESSENTRY32W entry{}; entry.dwSize=sizeof(entry);
|
||||
for (BOOL more=Process32FirstW(snapshot.get(),&entry);more;more=Process32NextW(snapshot.get(),&entry)) {
|
||||
if (_wcsicmp(entry.szExeFile,L"ttdownloader.exe") && _wcsicmp(entry.szExeFile,L"ttdownloader_d.exe")) continue;
|
||||
DWORD candidateSession=0;
|
||||
if (!ProcessIdToSessionId(entry.th32ProcessID,&candidateSession) || candidateSession!=session) continue;
|
||||
Handle process(OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION,FALSE,entry.th32ProcessID),&CloseHandle);
|
||||
if (process && UserSid(process.get())==sid) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
bool Complete(HANDLE pipe,OVERLAPPED& operation,HANDLE stop,ULONGLONG deadline,DWORD& done) {
|
||||
HANDLE waits[]={operation.hEvent,stop};
|
||||
ULONGLONG now=GetTickCount64();
|
||||
@@ -63,8 +82,12 @@ std::string Exchange(const std::string& input,const std::wstring& name) {
|
||||
}
|
||||
if (pipe.get()==INVALID_HANDLE_VALUE) {
|
||||
DWORD error=GetLastError(); pipe.release();
|
||||
if (error==ERROR_FILE_NOT_FOUND && ClientRunning())
|
||||
return Serialize(Reply("client_not_ready",
|
||||
"客户端已运行,但浏览器接口未就绪。请完全退出旧客户端(包括托盘),再启动新版 TTDownloader。"));
|
||||
return Serialize(Reply(error==ERROR_FILE_NOT_FOUND?"client_not_running":"connection_failed",
|
||||
error==ERROR_FILE_NOT_FOUND?"桌面客户端未运行,请先启动 TTDownloader":"桌面客户端繁忙或连接失败"));
|
||||
error==ERROR_FILE_NOT_FOUND?"未找到当前用户会话的客户端,请启动新版 TTDownloader":
|
||||
"桌面客户端繁忙或连接失败(Windows 错误 "+std::to_string(error)+")"));
|
||||
}
|
||||
ULONGLONG deadline=GetTickCount64()+28000;
|
||||
auto json=input;
|
||||
|
||||
@@ -89,7 +89,7 @@ std::string Serialize(const Message& fields) {
|
||||
}
|
||||
std::string Get(const Message& fields,const std::string& key) { auto it=fields.find(key); return it==fields.end()?"":it->second; }
|
||||
bool Validate(const Message& fields,std::string& error) {
|
||||
static const std::set<std::string> allowed={"action","request_id","url","referrer","user_agent","filename","method"};
|
||||
static const std::set<std::string> allowed={"action","request_id","url","referrer","user_agent","filename","method","confirmation"};
|
||||
for (const auto& [key,value]:fields) {
|
||||
if (!allowed.count(key) || value.find('\0')!=std::string::npos) { error="不支持的字段"; return false; }
|
||||
for (unsigned char c:value) if (c<32 || c==127) { error="字段不能含控制字符"; return false; }
|
||||
@@ -97,8 +97,9 @@ bool Validate(const Message& fields,std::string& error) {
|
||||
const auto action=Get(fields,"action"),id=Get(fields,"request_id");
|
||||
if (id.empty() || id.size()>80) { error="请求编号无效"; return false; }
|
||||
for (unsigned char c:id) if (!std::isalnum(c) && c!='-') { error="请求编号无效"; return false; }
|
||||
if (action=="ping" && fields.size()<=2) return true;
|
||||
if (action!="add" || Get(fields,"method")!="GET" || !HttpUrl(Get(fields,"url"))
|
||||
if ((action=="ping" || action=="query" || action=="cancel") && fields.size()<=2) return true;
|
||||
if (action!="add" || (!Get(fields,"confirmation").empty() && Get(fields,"confirmation")!="required")
|
||||
|| Get(fields,"method")!="GET" || !HttpUrl(Get(fields,"url"))
|
||||
|| (!Get(fields,"referrer").empty() && !HttpUrl(Get(fields,"referrer")))
|
||||
|| Get(fields,"user_agent").size()>2048 || Get(fields,"filename").size()>1024) {
|
||||
error="仅支持 HTTP/HTTPS GET 下载地址及合法上下文"; return false;
|
||||
|
||||
@@ -1,5 +1,8 @@
|
||||
#include "../shared/protocol.h"
|
||||
#include "../shared/pipe.h"
|
||||
#include "../native/client_connection.h"
|
||||
#include "../shared/command_line.h"
|
||||
#include "../../client/src/startup_options.h"
|
||||
#include <sstream>
|
||||
#include <iostream>
|
||||
#include <stdexcept>
|
||||
@@ -8,9 +11,57 @@ using namespace browser_bridge;
|
||||
static void Check(bool ok,const char* text) { if (!ok) throw std::runtime_error(text); }
|
||||
int main() {
|
||||
try {
|
||||
StartupOptions startup;
|
||||
Check(ParseStartupCommandLine(L"ttdownloader.exe",startup) && !startup.show_add,"normal startup has no add dialog");
|
||||
Check(ParseStartupCommandLine(L"ttdownloader.exe --add",startup) && startup.show_add && startup.url.empty(),"empty add dialog argument");
|
||||
for (const auto& url:{L"https://example.test/中文.zip?a=1&b=2",L"http://127.0.0.1/file.zip?token=a%20b"}) {
|
||||
Check(ParseStartupCommandLine(L"ttdownloader.exe --add "+QuoteArgument(url),startup) && startup.show_add && startup.url==url,"cold startup URL argument");
|
||||
Check(ParseStartupCommandLine(L"ttdownloader.exe "+QuoteArgument(url),startup) && startup.url==url,"bare URL startup argument");
|
||||
}
|
||||
for (const auto& bad:{L"ttdownloader.exe --unknown",L"ttdownloader.exe --add https://example.test/ extra",L"ttdownloader.exe file:///C:/test",L"ttdownloader.exe --add https://user:secret@example.test/"})
|
||||
Check(!ParseStartupCommandLine(bad,startup),"reject invalid startup arguments");
|
||||
Message launch{{"action","add"},{"confirmation","required"},{"request_id","startup-1"},{"method","GET"},
|
||||
{"url","https://example.test/中文.zip?q=a%20b&x=1"},{"user_agent","test \\\"quoted\\\" agent\\"},{"referrer","https://example.test/"}};
|
||||
auto command=QuoteArgument(L"C:\\含空格 path\\ttdownloader.exe")+L" --browser-request "+QuoteArgument(platform::FromUtf8(Serialize(launch)));
|
||||
Check(ParseStartupCommandLine(command,startup) && startup.browser_request==launch,"quoted browser startup preserves UTF-8, context and request identity");
|
||||
COPYDATASTRUCT forwarded{kStartupCopyDataTag,static_cast<DWORD>((command.size()+1)*sizeof(wchar_t)),command.data()};
|
||||
Check(DecodeStartupCopyData(&forwarded,startup) && startup.browser_request==launch,"warm-start payload uses the same argument parser");
|
||||
forwarded.cbData-=sizeof(wchar_t); Check(!DecodeStartupCopyData(&forwarded,startup),"reject unterminated startup IPC");
|
||||
forwarded.cbData=65536; Check(!DecodeStartupCopyData(&forwarded,startup),"reject oversized startup IPC before reading it");
|
||||
for (const std::wstring value:{L"",L"a b",L"end\\",L"a\\\"b",L"中文 & % ^ |"}) {
|
||||
int argc=0; auto args=CommandLineToArgvW((L"app.exe "+QuoteArgument(value)).c_str(),&argc);
|
||||
Check(args && argc==2 && value==args[1],"Windows argv escaping roundtrip"); LocalFree(args);
|
||||
}
|
||||
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 auto& action:{"query","cancel"}) {
|
||||
Check(Validate({{"action",action},{"request_id","confirm-1"}},error),"confirmation status protocol");
|
||||
Check(!Validate({{"action",action},{"request_id","confirm-1"},{"url","https://example.test/"}},error),"status action rejects extra payload");
|
||||
}
|
||||
for (const auto& initial:{"client_not_running","client_not_ready","connection_failed","awaiting_confirmation"}) {
|
||||
int exchanges=0,launches=0,waits=0;
|
||||
auto response=ForwardToClient(fields,Serialize(fields),[&](const std::string& json) {
|
||||
Check(json==Serialize(fields),"launch preserves original URL and context");
|
||||
return Serialize(Reply(++exchanges==1?initial:"awaiting_confirmation","",Get(fields,"request_id")));
|
||||
},[&] { ++launches; return std::string(); },[&](const std::string& json) {
|
||||
++waits; Message probe; Check(Parse(json,probe,error) && Get(probe,"action")=="ping","probe readiness before forwarding download");
|
||||
return Serialize(Reply("ready",""));
|
||||
});
|
||||
bool retry=std::string(initial)=="client_not_running" || std::string(initial)=="client_not_ready";
|
||||
Check(launches==(std::string(initial)=="client_not_running"?1:0) && waits==(retry?1:0) && exchanges==(retry?2:1),"launch once only when client is absent");
|
||||
}
|
||||
for (const auto& action:{"ping","query","cancel"}) {
|
||||
auto response=ForwardToClient({{"action",action},{"request_id","no-launch"}},"{}",
|
||||
[](const std::string&) { return Serialize(Reply("client_not_running","")); },
|
||||
[]()->std::string { throw std::runtime_error("passive request must not launch"); },
|
||||
[](const std::string&)->std::string { throw std::runtime_error("passive request must not wait for startup"); });
|
||||
Check(Parse(response,restored,error) && Get(restored,"status")=="client_not_running","passive check returns offline");
|
||||
}
|
||||
auto failed=ForwardToClient(fields,Serialize(fields),[](const std::string&) { return Serialize(Reply("client_not_running","")); },
|
||||
[] { return Serialize(Reply("launch_failed","missing executable")); },
|
||||
[](const std::string&)->std::string { throw std::runtime_error("must not wait after launch failure"); });
|
||||
Check(Parse(failed,restored,error) && Get(restored,"status")=="launch_failed","launch failure remains explicit");
|
||||
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");
|
||||
@@ -19,6 +70,16 @@ int main() {
|
||||
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());
|
||||
// A running older client has a main window but no browser endpoint.
|
||||
// This hidden test window never starts the application or opens its database.
|
||||
WNDCLASSW windowClass{}; windowClass.lpfnWndProc=DefWindowProcW;
|
||||
windowClass.hInstance=GetModuleHandleW(nullptr); windowClass.lpszClassName=L"TTDownloaderMainWindow";
|
||||
Check(RegisterClassW(&windowClass)!=0,"register legacy client test window");
|
||||
HWND legacy=CreateWindowW(windowClass.lpszClassName,L"",WS_OVERLAPPED,0,0,1,1,nullptr,nullptr,windowClass.hInstance,nullptr);
|
||||
Check(legacy!=nullptr,"create hidden legacy client window");
|
||||
auto missing=Exchange(Serialize({{"action","ping"},{"request_id","legacy-ping"}}),name);
|
||||
DestroyWindow(legacy); UnregisterClassW(windowClass.lpszClassName,windowClass.hInstance);
|
||||
Check(Parse(missing,restored,error) && Get(restored,"status")=="client_not_ready","running legacy client must not be reported as stopped");
|
||||
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));
|
||||
|
||||
@@ -74,7 +74,10 @@ test('worker restart retries the same request id; disabling auto restores browse
|
||||
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);
|
||||
await recover(m.api,async r=>{
|
||||
assert.equal(r.request_id,'test-1'); assert.equal(r.action,auto?'add':'cancel');
|
||||
return auto?{status:'accepted',request_id:r.request_id,task_id:'42'}:{status:'canceled'};
|
||||
},auto);
|
||||
assert.equal(m.item.state,auto?'interrupted':'in_progress'); assert.equal(m.item.paused,false);
|
||||
}
|
||||
});
|
||||
@@ -83,7 +86,8 @@ test('background worker wires observed GET to native acknowledgement before canc
|
||||
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 old=globalThis.chrome, oldTimeout=globalThis.setTimeout, timers=[];
|
||||
globalThis.setTimeout=(...args)=>{const timer=oldTimeout(...args); timers.push(timer); return timer;};
|
||||
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;}},
|
||||
@@ -95,7 +99,7 @@ test('background worker wires observed GET to native acknowledgement before canc
|
||||
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; }
|
||||
} finally { timers.forEach(clearTimeout); globalThis.setTimeout=oldTimeout; globalThis.chrome=old; }
|
||||
});
|
||||
|
||||
test('zero task id is not an acknowledgement', async () => {
|
||||
@@ -104,7 +108,7 @@ test('zero task id is not an acknowledgement', async () => {
|
||||
});
|
||||
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);
|
||||
await recover(m.api,async r=>{assert.equal(r.action,'cancel'); return {status:'canceled'};},true);
|
||||
assert.equal(m.item.paused,false); assert.deepEqual(m.events,[]);
|
||||
});
|
||||
test('storage failure during fallback must not strand a paused download', async () => {
|
||||
@@ -119,3 +123,50 @@ test('manual cross-site handoff does not leak source query parameters', () => {
|
||||
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');
|
||||
});
|
||||
|
||||
test('confirmation waits without canceling browser and queries the same request after restart', async () => {
|
||||
const m=mock();
|
||||
const pending=await handoff(m.api,m.item,request,async r=>({status:'awaiting_confirmation',request_id:r.request_id}));
|
||||
assert.equal(pending.status,'awaiting_confirmation'); assert.deepEqual(m.events,['pause']);
|
||||
assert.equal(m.data.pending_1.phase,'confirming');
|
||||
const results=await recover(m.api,async r=>{
|
||||
assert.deepEqual(r,{action:'query',request_id:request.request_id});
|
||||
return {status:'accepted',request_id:r.request_id,task_id:'42'};
|
||||
},true);
|
||||
assert.equal(results[0].status,'accepted'); assert.deepEqual(m.events,['pause','cancel']);
|
||||
});
|
||||
test('closing the desktop dialog restores browser download', async () => {
|
||||
const m=mock();
|
||||
await handoff(m.api,m.item,request,async r=>({status:'awaiting_confirmation',request_id:r.request_id}));
|
||||
await recover(m.api,async()=>({status:'canceled',message:'用户取消'}),true);
|
||||
assert.deepEqual(m.events,['pause','resume']); assert.equal(m.data.pending_1,undefined);
|
||||
});
|
||||
test('expired confirmation and disabled capture close the pending desktop dialog before resuming', async () => {
|
||||
for(const auto of [true,false]) {
|
||||
const m=mock();
|
||||
await handoff(m.api,m.item,request,async r=>({status:'awaiting_confirmation',request_id:r.request_id}));
|
||||
if(auto) m.data.pending_1.created=Date.now()-121000;
|
||||
await recover(m.api,async r=>{assert.equal(r.action,'cancel'); m.events.push('dismiss'); return {status:'canceled'};},auto);
|
||||
assert.deepEqual(m.events,['pause','dismiss','resume']);
|
||||
}
|
||||
});
|
||||
test('confirmation wins a simultaneous timeout only after a persisted acknowledgement', async () => {
|
||||
const m=mock();
|
||||
await handoff(m.api,m.item,request,async r=>({status:'awaiting_confirmation',request_id:r.request_id}));
|
||||
await recover(m.api,async r=>{assert.equal(r.action,'cancel'); return {status:'accepted',request_id:r.request_id,task_id:'42'};},false);
|
||||
assert.deepEqual(m.events,['pause','cancel']);
|
||||
});
|
||||
test('user resuming a waiting browser download dismisses the unconfirmed desktop dialog', async () => {
|
||||
const m=mock();
|
||||
await handoff(m.api,m.item,request,async r=>({status:'awaiting_confirmation',request_id:r.request_id}));
|
||||
m.item.paused=false;
|
||||
await recover(m.api,async r=>{assert.equal(r.action,'cancel'); return {status:'canceled'};},true);
|
||||
assert.deepEqual(m.events,['pause']); assert.equal(m.data.pending_1,undefined);
|
||||
});
|
||||
|
||||
test('storage failure after acceptance never resumes an already handed-off download', async () => {
|
||||
const m=mock(), set=m.api.storage.local.set;
|
||||
m.api.storage.local.set=async values=>{if(values.pending_1?.phase==='cancel') throw new Error('quota'); return set(values);};
|
||||
const result=await handoff(m.api,m.item,request,async r=>({status:'accepted',request_id:r.request_id,task_id:'42'}));
|
||||
assert.equal(result.status,'accepted'); assert.deepEqual(m.events,['pause','cancel']);
|
||||
});
|
||||
Reference in new issue
Block a user