新增 Chrome 下载接管扩展与 C++ 本地通信组件
实现链接右键发送、手动地址输入和默认关闭的可选 GET 自动接管,支持站点与文件类型过滤。通过 Native Messaging 和当前用户命名管道在任务入库后确认接管,失败恢复浏览器下载并持久化交接状态。保存请求编号、Referer 与 User-Agent,补充本地注册入口、集成包说明及扩展/stdio/IPC/HTTP 回归测试。
This commit is contained in:
1 parent
6c810c3b4f
commit
028fec64be
41 files changed
+1081
-18
No files matched your search
@@ -0,0 +1,49 @@
|
||||
# TTDownloader 浏览器下载接管
|
||||
|
||||
Chrome Manifest V3 扩展 + 全 C++ Native Messaging Host + 桌面下载引擎。Edge 可加载同一扩展目录。
|
||||
|
||||
## 安装 Chrome 版本
|
||||
|
||||
1. 源码用户先在仓库根目录运行 `build.cmd Release`;打包版本已附带可执行文件。编译得到 `client/bin/ttdownloader.exe` 与 `client/bin/ttdownloader_native_host.exe`。先退出旧客户端,再启动新版本。
|
||||
2. 运行 `browser/register-host.cmd`,将 Host 注册到当前用户 Chrome 的 NativeMessagingHosts(32 位注册表视图)。无需管理员、不依赖 PowerShell;Host 配置写入 `%LOCALAPPDATA%/TTDownloader/native_host.json`。
|
||||
3. 打开 Chrome 的 `chrome://extensions`,启用开发者模式,选择“加载已解压的扩展程序”,选中 `browser/chrome/`。
|
||||
4. 点击扩展按钮,选择“检查桌面连接”。扩展 ID 由 manifest 中的固定公开 key 决定,必须与 Host 的 allowed_origins 一致;不要删除或改写 key。
|
||||
|
||||
卸载本地注册:运行 `browser/unregister-host.cmd`。它只移除当前用户注册项,保留客户端、下载文件和任务数据库。移动 Host 后需重新注册。
|
||||
|
||||
Edge:在 `edge://extensions` 加载同一目录,并执行 `client/bin/ttdownloader_native_host.exe --register edge`;也可以用 `--register both` 同时注册。卸载对应使用 `--unregister edge/both`。
|
||||
|
||||
## 使用方式
|
||||
|
||||
- 右键点击 HTTP/HTTPS 链接,选择“使用 TTDownloader 下载”。
|
||||
- 在扩展弹窗粘贴下载地址后发送。客户端接收并入库后显示成功;重复会明确显示已有任务。
|
||||
- 默认不自动接管。勾选“自动接管”,保存时按 Chrome 提示授予可选站点访问与 webRequest 权限。可指定站点和文件类型;留空表示不限制。
|
||||
- 站点以空格或逗号分隔,支持 `example.com` 精确匹配和 `*.example.com` 子域匹配。文件类型如 `.zip,.exe,.mp4`,按文件名或 URL 路径后缀匹配。
|
||||
|
||||
自动接管先将恢复记录写入扩展本地存储,再暂停浏览器下载。桌面任务入库确认后才取消浏览器下载。通信失败、客户端未启动或重复任务会保留/恢复浏览器下载。失败会显示通知、工具栏 `!` 和弹窗状态。后台重启时重用同一个请求编号,避免重复创建桌面任务;已恢复的浏览器任务不会再次被暂停。
|
||||
|
||||
桌面客户端需已启动,首版不自动启动客户端。入库确认代表任务已交给桌面引擎,并不代表目标服务器已经返回下载内容。
|
||||
|
||||
## 支持范围
|
||||
|
||||
- 仅 HTTP/HTTPS GET;自动接管要求最近观察到 GET 请求。POST、blob/data、其他扩展创建的下载、隐身下载、浏览器标记的危险下载、用户已暂停的下载和无法确认请求方法的下载留在浏览器。
|
||||
- 提交 Referer、User-Agent、文件名提示和请求编号。自动接管使用浏览器提供的 Referer;手动链接跨站只传来源 origin,HTTPS 降级不传来源。文件名只取 basename 并经过客户端清理,不接受浏览器指定任意保存路径;下载目录由桌面端决定。
|
||||
- 不读取或转发 Cookie、登录凭据或 POST 内容。依赖登录态、一次性请求或特殊认证的网站可能仍需浏览器下载,应从自动规则中排除。
|
||||
- 不处理视频网站解析、BT 或磁力链接。
|
||||
- 扩展使用 Chrome 109 及以上 API;桌面 Host 以 Windows 7 SP1 x64 为兼容目标。当前通过构建及协议自动化测试,尚未在真实 Chrome/Edge 加载或 Windows 7 虚拟机完成验收。
|
||||
|
||||
## 结构与边界
|
||||
|
||||
`扩展 → Native Messaging Host → 当前用户/当前会话命名管道 → 下载引擎命令队列 → TaskStore`。
|
||||
|
||||
Host 限制扩展来源和 64KiB 消息长度,按原生消息协议使用 4 字节小端长度 + UTF-8 JSON,stdout 不输出普通日志。IPC 限制当前用户与 SYSTEM,拒绝远程连接。未安装、客户端未启动、繁忙、重复或失败都有单独状态。
|
||||
|
||||
任务只在引擎线程中访问数据库。新增 request_id/referrer/user_agent 列由 TaskStore 对旧库逐列补齐;恢复后保留必要上下文。浏览器请求错误不会误关闭桌面手动添加窗口。
|
||||
|
||||
## 测试
|
||||
|
||||
运行 `test.cmd Debug` / `test.cmd Release`,需要开发机安装 Node.js 20+ 和 Python,客户端运行不依赖它们。
|
||||
|
||||
覆盖扩展过滤、确认前不取消、离线/重复/断线恢复、恢复失败、后台重启、用户恢复下载、实际后台事件接线;Native Host UTF-8/帧长度/来源校验;用户隔离命名管道与取消 I/O;临时 SQLite 上下文保存恢复;HTTP Referer/User-Agent 发送和头注入拒绝。测试不安装扩展、不修改用户注册表、不向真实任务库添加下载。
|
||||
|
||||
协议参考:[Chrome Native Messaging](https://developer.chrome.com/docs/extensions/develop/concepts/native-messaging)、[downloads API](https://developer.chrome.com/docs/extensions/reference/api/downloads)、[contextMenus API](https://developer.chrome.com/docs/extensions/reference/api/contextMenus)。
|
||||
@@ -0,0 +1,88 @@
|
||||
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;
|
||||
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 ok = ['accepted', 'ready'].includes(result.status);
|
||||
await chrome.action.setBadgeText({text: 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; });
|
||||
return result;
|
||||
}
|
||||
function native(request) {
|
||||
return new Promise((resolve, reject) => {
|
||||
let port, timer, finished = false;
|
||||
const done = (error, value) => { if (finished) return; finished = true; clearTimeout(timer); port?.disconnect(); error ? reject(error) : resolve(value); };
|
||||
try {
|
||||
port = chrome.runtime.connectNative(HOST);
|
||||
port.onMessage.addListener(reply => {
|
||||
if (reply?.request_id !== request.request_id) return done(new Error('本地响应编号不匹配,请检查桌面任务列表'));
|
||||
done(null, reply);
|
||||
});
|
||||
port.onDisconnect.addListener(() => done(new Error('本地组件未连接:' + (chrome.runtime.lastError?.message || '通信中断') + ';请检查注册和桌面客户端')));
|
||||
timer = setTimeout(() => done(new Error('本地通信超时,请检查桌面任务列表')), 30000);
|
||||
port.postMessage(request);
|
||||
} catch (error) { done(error); }
|
||||
});
|
||||
}
|
||||
const requestObserver = details => {
|
||||
const url = httpUrl(details.url); if (!url) return;
|
||||
observed.set(url, {method: details.method, time: Date.now()});
|
||||
if (observed.size > 512) observed.delete(observed.keys().next().value);
|
||||
};
|
||||
async function configure() {
|
||||
if (chrome.webRequest?.onBeforeRequest.hasListener(requestObserver)) chrome.webRequest.onBeforeRequest.removeListener(requestObserver);
|
||||
const allowed = await chrome.permissions.contains({permissions: ['webRequest'], origins: ['http://*/*', 'https://*/*']});
|
||||
const settings = await config();
|
||||
if (settings.auto && !allowed) { await chrome.storage.local.set({config: {...settings, auto: false}}); await status({status: 'error', message: '站点权限未授予或已撤销,自动接管已停用'}); }
|
||||
if (settings.auto && allowed) chrome.webRequest.onBeforeRequest.addListener(requestObserver, {urls: ['http://*/*', 'https://*/*']});
|
||||
else observed.clear();
|
||||
}
|
||||
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); })()
|
||||
.catch(error => status({status: 'error', message: '恢复下载状态失败:' + error.message})).finally(() => { recovery = null; });
|
||||
return recovery;
|
||||
}
|
||||
chrome.runtime.onInstalled.addListener(() => {
|
||||
chrome.contextMenus.removeAll(() => chrome.contextMenus.create({id: 'send', title: '使用 TTDownloader 下载', contexts: ['link'], targetUrlPatterns: ['http://*/*', 'https://*/*']}));
|
||||
chrome.alarms.create('recover', {periodInMinutes: 1}); configure().catch(console.error);
|
||||
});
|
||||
chrome.runtime.onStartup.addListener(() => { configure().catch(console.error); restorePending(); });
|
||||
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.contextMenus.onClicked.addListener(async info => {
|
||||
if (info.menuItemId !== 'send') return;
|
||||
try { await status(await native(requestFor(info.linkUrl, linkReferrer(info.pageUrl, info.linkUrl)))); }
|
||||
catch (error) { await status({status: 'error', message: error.message}); }
|
||||
});
|
||||
chrome.downloads.onCreated.addListener(async item => {
|
||||
if (recovery) await recovery;
|
||||
const url = httpUrl(item.finalUrl || item.url);
|
||||
if (!eligible(item, await config(), observed.get(url) || observed.get(httpUrl(item.url))) || busy.has(item.id)) return;
|
||||
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); }
|
||||
});
|
||||
chrome.runtime.onMessage.addListener((message, sender, respond) => {
|
||||
if (sender.id !== chrome.runtime.id || !sender.url?.startsWith(chrome.runtime.getURL(''))) return;
|
||||
(async () => {
|
||||
try {
|
||||
if (message.action === 'ping') return await status(await native({action: 'ping', request_id: crypto.randomUUID()}));
|
||||
if (message.action === 'send') return await status(await native(requestFor(message.url)));
|
||||
return {status: 'error', message: '不支持的操作'};
|
||||
} catch (error) { return status({status: 'error', message: error.message}); }
|
||||
})().then(respond);
|
||||
return true;
|
||||
});
|
||||
// Register synchronously so MV3 can deliver the first request after a worker restart.
|
||||
try { chrome.webRequest?.onBeforeRequest.addListener(requestObserver, {urls: ['http://*/*', 'https://*/*']}); } catch {}
|
||||
chrome.alarms.create('recover', {periodInMinutes: 1});
|
||||
configure().catch(console.error);
|
||||
restorePending();
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 491 B |
@@ -0,0 +1,88 @@
|
||||
export const DEFAULTS = Object.freeze({auto: false, sites: '', extensions: ''});
|
||||
export function httpUrl(value) {
|
||||
try { const u = new URL(value); if (!['http:', 'https:'].includes(u.protocol) || u.username || u.password) return ''; u.hash = ''; return u.href; } catch { return ''; }
|
||||
}
|
||||
export function eligible(item, config, observed, now = Date.now()) {
|
||||
if (!config.auto || item.state !== 'in_progress' || item.paused || item.incognito || item.byExtensionId || (item.danger && item.danger !== 'safe')) return false;
|
||||
const url = httpUrl(item.finalUrl || item.url);
|
||||
if (!url || !observed || observed.method !== 'GET' || now - observed.time > 15000) return false;
|
||||
const parsed = new URL(url);
|
||||
const sites = config.sites.split(/[\s,]+/).filter(Boolean).map(s => s.toLowerCase());
|
||||
if (sites.length && !sites.some(s => s.startsWith('*.') ? parsed.hostname.endsWith(s.slice(1)) : parsed.hostname === s)) return false;
|
||||
const types = config.extensions.toLowerCase().split(/[\s,]+/).filter(Boolean).map(s => s.startsWith('.') ? s : '.' + s);
|
||||
const name = (item.filename || parsed.pathname).toLowerCase();
|
||||
return !types.length || types.some(type => name.endsWith(type));
|
||||
}
|
||||
export function linkReferrer(source, target) {
|
||||
const from = httpUrl(source), to = httpUrl(target); if (!from || !to) return '';
|
||||
const a = new URL(from), b = new URL(to);
|
||||
if (a.protocol === 'https:' && b.protocol === 'http:') return '';
|
||||
return a.origin === b.origin ? a.href : a.origin + '/';
|
||||
}
|
||||
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,
|
||||
referrer: httpUrl(referrer), filename: filename.split(/[\\/]/).pop().slice(0, 240), user_agent: navigator.userAgent};
|
||||
}
|
||||
const key = id => `pending_${id}`;
|
||||
const save = (api, record) => api.storage.local.set({[key(record.id)]: record});
|
||||
const remove = (api, id) => api.storage.local.remove(key(id));
|
||||
const current = async (api, id) => (await api.downloads.search({id}))[0];
|
||||
async function restore(api, record, message) {
|
||||
record.phase = 'resume';
|
||||
try { await save(api, record); } catch {} // Recovery must still resume when storage is temporarily unavailable.
|
||||
try {
|
||||
const item = await current(api, record.id);
|
||||
if (item?.state === 'in_progress' && item.paused) await api.downloads.resume(record.id);
|
||||
try { await remove(api, record.id); } catch {}
|
||||
return {status: 'fallback', message: message + ';已保留或恢复浏览器下载'};
|
||||
} catch {
|
||||
return {status: 'recovery_pending', message: message + ';恢复失败,已保留恢复记录,请在浏览器下载页继续下载'};
|
||||
}
|
||||
}
|
||||
async function finish(api, record) {
|
||||
try {
|
||||
const item = await current(api, record.id);
|
||||
if (item?.state === 'in_progress' && !item.paused) {
|
||||
await remove(api, record.id);
|
||||
return {status: 'warning', message: '桌面已接收任务,但浏览器下载已被恢复;请检查是否重复下载'};
|
||||
}
|
||||
if (item?.state === 'in_progress') await api.downloads.cancel(record.id);
|
||||
await remove(api, record.id);
|
||||
return {status: 'accepted', message: '已交给 TTDownloader,任务编号 ' + record.task_id};
|
||||
} catch {
|
||||
return {status: 'recovery_pending', message: '桌面已接收任务,浏览器取消失败,将继续重试'};
|
||||
}
|
||||
}
|
||||
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);
|
||||
if (record.phase === 'resume') return restore(api, record, '继续恢复浏览器下载');
|
||||
try {
|
||||
// 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))
|
||||
return restore(api, record, reply?.message || '桌面未确认接管');
|
||||
record.phase = 'cancel'; record.task_id = reply.task_id; await save(api, record);
|
||||
return finish(api, record);
|
||||
} catch (error) {
|
||||
return restore(api, record, error.message || '本地通信失败,结果未确认');
|
||||
}
|
||||
}
|
||||
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 (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, '接管未完成'));
|
||||
else outcomes.push(await handoff(api, item, record.request, sendNative, record));
|
||||
}
|
||||
return outcomes;
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
{
|
||||
"manifest_version": 3,
|
||||
"name": "TTDownloader 下载接管",
|
||||
"description": "将主动发起的 HTTP/HTTPS 下载交给 TTDownloader,自动接管默认关闭。",
|
||||
"version": "0.1.0",
|
||||
"minimum_chrome_version": "109",
|
||||
"key": "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAvbbxlyA8oQYALtekWYplS8AuRDPyQmQX51/zpbfYT10Zpsbs+8yd0/l4aP9ByJyjs0N3oI0EsFcA6FPqWK+/SPDeMqZiyxSiIGzcy+zCjYiKelUSzBz80gayXk6R509YV2GKbpt9LOliK92GQy+bacblVScXtqKqmjrubTo+WplRXnPjS0pv2Kx7saSyX10ajjsOTmg1kNaN3x1tCbkOSXR+46idt5VC78sSvixfqwdD0tIqcH7TI6jN0t3nvQakFgfYlcjAgAJrC1PYZdoZMAT2dOjyXV73Bf2y7NHvRQtkDj37Cm88AOH6FncvME7zUbiGrfmZx+ik+rdBQHUULQIDAQAB",
|
||||
"permissions": [
|
||||
"nativeMessaging",
|
||||
"contextMenus",
|
||||
"storage",
|
||||
"downloads",
|
||||
"alarms",
|
||||
"notifications"
|
||||
],
|
||||
"optional_permissions": [
|
||||
"webRequest"
|
||||
],
|
||||
"optional_host_permissions": [
|
||||
"http://*/*",
|
||||
"https://*/*"
|
||||
],
|
||||
"background": {
|
||||
"service_worker": "background.js",
|
||||
"type": "module"
|
||||
},
|
||||
"action": {
|
||||
"default_popup": "popup.html",
|
||||
"default_title": "TTDownloader"
|
||||
},
|
||||
"icons": {
|
||||
"128": "icon.png"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
body{width:340px;margin:18px;font:14px "Microsoft YaHei",sans-serif;color:#273449;background:#f0f3f8}h1{font-size:20px}form{border-top:1px solid #bbc8d8;margin-top:16px;padding-top:14px}label{display:block;margin:10px 0 6px}input:not([type=checkbox]),textarea{box-sizing:border-box;width:100%;padding:8px;border:1px solid #9aabc0;border-radius:3px}button{padding:8px 12px;margin-top:8px;border:1px solid #307ef3;color:#245cb0;background:transparent;border-radius:3px;cursor:pointer}button:disabled{opacity:.5;cursor:wait}#status{overflow-wrap:anywhere;white-space:pre-line}.note{color:#64748b;font-size:12px;line-height:1.6}
|
||||
@@ -0,0 +1,5 @@
|
||||
<!doctype html><html lang="zh-CN"><meta charset="utf-8"><title>TTDownloader</title><link rel="stylesheet" href="popup.css">
|
||||
<body><h1>TTDownloader</h1><p id="status" role="status">正在读取状态…</p><button id="ping">检查桌面连接</button>
|
||||
<form id="send"><label for="url">下载地址</label><input id="url" type="url" placeholder="https://…" required><button>交给 TTDownloader</button></form>
|
||||
<form id="settings"><label><input id="auto" type="checkbox"> 自动接管已确认的 GET 下载</label><label for="sites">站点规则(留空表示全部)</label><textarea id="sites" placeholder="example.com, *.example.org"></textarea><label for="extensions">文件类型(留空表示全部)</label><input id="extensions" placeholder=".zip, .exe, .mp4"><button>保存接管设置</button></form>
|
||||
<p class="note">也可右键点击链接发送。自动接管默认关闭;失败会恢复浏览器下载。首版不接管 POST、blob、登录 Cookie 或无法确认方法的下载。</p><script type="module" src="popup.js"></script></body></html>
|
||||
@@ -0,0 +1,25 @@
|
||||
import {DEFAULTS} from './logic.mjs';
|
||||
const el = id => document.getElementById(id);
|
||||
const cfg = {...DEFAULTS, ...(await chrome.storage.local.get('config')).config};
|
||||
for (const field of ['sites', 'extensions']) el(field).value = cfg[field];
|
||||
el('auto').checked = cfg.auto;
|
||||
const show = result => { el('status').textContent = result?.message || '尚无接管记录;可先检查桌面连接。'; };
|
||||
show((await chrome.storage.local.get('lastResult')).lastResult);
|
||||
chrome.storage.onChanged.addListener(changes => { if (changes.lastResult) show(changes.lastResult.newValue); });
|
||||
async function send(message, button) {
|
||||
button.disabled = true;
|
||||
try { show(await chrome.runtime.sendMessage(message)); } catch (error) { show({message: error.message}); }
|
||||
finally { button.disabled = false; }
|
||||
}
|
||||
el('ping').onclick = event => send({action: 'ping'}, event.target);
|
||||
el('send').onsubmit = event => { event.preventDefault(); send({action: 'send', url: el('url').value}, event.submitter); };
|
||||
el('settings').onsubmit = async event => {
|
||||
event.preventDefault();
|
||||
try {
|
||||
if (el('auto').checked && !(await chrome.permissions.request({permissions: ['webRequest'], origins: ['http://*/*', 'https://*/*']}))) {
|
||||
el('auto').checked = false; return show({message: '未授权站点访问,自动接管保持关闭。'});
|
||||
}
|
||||
await chrome.storage.local.set({config: {auto: el('auto').checked, sites: el('sites').value.trim(), extensions: el('extensions').value.trim()}});
|
||||
show({message: '接管设置已保存。'});
|
||||
} catch (error) { show({message: error.message}); }
|
||||
};
|
||||
@@ -0,0 +1,73 @@
|
||||
#include "../shared/protocol.h"
|
||||
#include "../shared/pipe.h"
|
||||
#include "../shared/identity.h"
|
||||
#include <fcntl.h>
|
||||
#include <io.h>
|
||||
#include <iostream>
|
||||
#include <vector>
|
||||
namespace {
|
||||
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;
|
||||
}
|
||||
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);
|
||||
DWORD n=GetModuleFileNameW(nullptr,executable.data(),static_cast<DWORD>(executable.size()));
|
||||
DWORD m=GetEnvironmentVariableW(L"LOCALAPPDATA",local.data(),static_cast<DWORD>(local.size()));
|
||||
if (!n || n>=executable.size() || !m || m>=local.size()) return 1;
|
||||
std::wstring directory=std::wstring(local.data())+L"\\TTDownloader",manifest=directory+L"\\native_host.json";
|
||||
if (!remove) {
|
||||
if (!CreateDirectoryW(directory.c_str(),nullptr) && GetLastError()!=ERROR_ALREADY_EXISTS) return 1;
|
||||
auto json=browser_bridge::Serialize({{"name",browser_bridge::kHostName},{"description","TTDownloader native download bridge"},{"path",Utf8(executable.data())},{"type","stdio"}});
|
||||
json.pop_back(); json+=",\"allowed_origins\":[\""+std::string(browser_bridge::kExtensionOrigin)+"\"]}";
|
||||
HANDLE file=CreateFileW(manifest.c_str(),GENERIC_WRITE,0,nullptr,CREATE_ALWAYS,FILE_ATTRIBUTE_NORMAL,nullptr);
|
||||
if (file==INVALID_HANDLE_VALUE) return 1;
|
||||
DWORD written=0; bool ok=WriteFile(file,json.data(),static_cast<DWORD>(json.size()),&written,nullptr) && written==json.size();
|
||||
CloseHandle(file); if (!ok) return 1;
|
||||
}
|
||||
for (const auto& target : {std::string("chrome"),std::string("edge")}) {
|
||||
if (browser!="both" && browser!=target) continue;
|
||||
auto key=std::wstring(target=="chrome"?L"Software\\Google\\Chrome\\NativeMessagingHosts\\":L"Software\\Microsoft\\Edge\\NativeMessagingHosts\\")+L"com.ttstd.ttdownloader";
|
||||
if (remove) {
|
||||
LSTATUS status=RegDeleteKeyExW(HKEY_CURRENT_USER,key.c_str(),KEY_WOW64_32KEY,0);
|
||||
if (status!=ERROR_SUCCESS && status!=ERROR_FILE_NOT_FOUND) return 1;
|
||||
} else {
|
||||
HKEY handle=nullptr;
|
||||
if (RegCreateKeyExW(HKEY_CURRENT_USER,key.c_str(),0,nullptr,0,KEY_SET_VALUE|KEY_WOW64_32KEY,nullptr,&handle,nullptr)!=ERROR_SUCCESS) return 1;
|
||||
LSTATUS status=RegSetValueExW(handle,nullptr,0,REG_SZ,reinterpret_cast<const BYTE*>(manifest.c_str()),static_cast<DWORD>((manifest.size()+1)*sizeof(wchar_t)));
|
||||
RegCloseKey(handle); if (status!=ERROR_SUCCESS) return 1;
|
||||
}
|
||||
}
|
||||
std::cout<<(remove?"Unregistered":"Registered")<<" TTDownloader Native Messaging Host for "<<browser<<".\n"; return 0;
|
||||
}
|
||||
}
|
||||
int main(int argc,char** argv) {
|
||||
if (argc>=2 && (std::string(argv[1])=="--register" || std::string(argv[1])=="--unregister")) {
|
||||
int result=RegisterHost(argc>=3?argv[2]:"chrome",std::string(argv[1])=="--unregister");
|
||||
if (result) std::cerr<<"Native host registration failed. Check the application path and current-user registry access.\n";
|
||||
return result;
|
||||
}
|
||||
if (argc<2 || std::string(argv[1])!=browser_bridge::kExtensionOrigin) return 1;
|
||||
_setmode(_fileno(stdin),_O_BINARY); _setmode(_fileno(stdout),_O_BINARY);
|
||||
std::ios::sync_with_stdio(false);
|
||||
std::string json;
|
||||
while (browser_bridge::ReadFrame(std::cin,json)) {
|
||||
browser_bridge::Message fields; std::string error,response;
|
||||
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);
|
||||
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()
|
||||
|| (!browser_bridge::Get(reply,"request_id").empty() && browser_bridge::Get(reply,"request_id")!=expected)
|
||||
|| (browser_bridge::Get(reply,"status")=="accepted" && browser_bridge::Get(reply,"request_id")!=expected))
|
||||
reply=browser_bridge::Reply("connection_failed","桌面返回无效消息或请求编号不匹配");
|
||||
reply["request_id"]=expected;
|
||||
response=browser_bridge::Serialize(reply);
|
||||
}
|
||||
if (!browser_bridge::WriteFrame(std::cout,response)) return 1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
@@ -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>{F8C0CDE7-9F20-4D81-A472-73BA1F151505}</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\</OutDir><IntDir>$(ProjectDir)obj\$(Configuration)\</IntDir><TargetName>ttdownloader_native_host</TargetName><TargetName Condition="'$(Configuration)'=='Debug'">ttdownloader_native_host_d</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="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>
|
||||
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
|
||||
</Project>
|
||||
@@ -0,0 +1 @@
|
||||
{"private":true,"type":"module"}
|
||||
@@ -0,0 +1,3 @@
|
||||
@echo off
|
||||
"%~dp0..\client\bin\ttdownloader_native_host.exe" --register chrome
|
||||
exit /b %ERRORLEVEL%
|
||||
@@ -0,0 +1,5 @@
|
||||
#pragma once
|
||||
namespace browser_bridge {
|
||||
inline constexpr char kExtensionOrigin[]="chrome-extension://mlidghkaimgommidibnmcflafblbhcdb/";
|
||||
inline constexpr char kHostName[]="com.ttstd.ttdownloader";
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
#include "pipe.h"
|
||||
#include "protocol.h"
|
||||
#include <sddl.h>
|
||||
#include <vector>
|
||||
#include <memory>
|
||||
#include <sstream>
|
||||
#include <utility>
|
||||
#pragma comment(lib,"advapi32.lib")
|
||||
namespace browser_bridge {
|
||||
namespace {
|
||||
using Handle=std::unique_ptr<void,decltype(&CloseHandle)>;
|
||||
std::wstring UserSid() {
|
||||
HANDLE raw=nullptr;
|
||||
if (!OpenProcessToken(GetCurrentProcess(),TOKEN_QUERY,&raw)) return {};
|
||||
Handle token(raw,&CloseHandle); DWORD size=0;
|
||||
GetTokenInformation(token.get(),TokenUser,nullptr,0,&size);
|
||||
std::vector<char> buffer(size);
|
||||
if (!size || !GetTokenInformation(token.get(),TokenUser,buffer.data(),size,&size)) return {};
|
||||
LPWSTR sid=nullptr;
|
||||
if (!ConvertSidToStringSidW(reinterpret_cast<TOKEN_USER*>(buffer.data())->User.Sid,&sid)) return {};
|
||||
std::wstring result(sid); LocalFree(sid); return result;
|
||||
}
|
||||
bool Complete(HANDLE pipe,OVERLAPPED& operation,HANDLE stop,ULONGLONG deadline,DWORD& done) {
|
||||
HANDLE waits[]={operation.hEvent,stop};
|
||||
ULONGLONG now=GetTickCount64();
|
||||
DWORD timeout=now>=deadline?0:static_cast<DWORD>(deadline-now);
|
||||
DWORD wait=WaitForMultipleObjects(stop?2:1,waits,FALSE,timeout);
|
||||
if (wait!=WAIT_OBJECT_0) { CancelIoEx(pipe,&operation); GetOverlappedResult(pipe,&operation,&done,TRUE); return false; }
|
||||
return GetOverlappedResult(pipe,&operation,&done,FALSE)!=FALSE;
|
||||
}
|
||||
bool Bytes(HANDLE pipe,void* data,DWORD size,bool write,HANDLE stop,ULONGLONG deadline) {
|
||||
Handle event(CreateEventW(nullptr,TRUE,FALSE,nullptr),&CloseHandle);
|
||||
if (!event) return false;
|
||||
auto* bytes=static_cast<char*>(data); DWORD total=0;
|
||||
while (total<size) {
|
||||
OVERLAPPED operation{}; operation.hEvent=event.get(); ResetEvent(event.get()); DWORD done=0;
|
||||
BOOL ok=write?WriteFile(pipe,bytes+total,size-total,&done,&operation):ReadFile(pipe,bytes+total,size-total,&done,&operation);
|
||||
if (!ok && (GetLastError()!=ERROR_IO_PENDING || !Complete(pipe,operation,stop,deadline,done))) return false;
|
||||
if (!done) return false; total+=done;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
bool Frame(HANDLE pipe,std::string& json,bool write,HANDLE stop,ULONGLONG deadline) {
|
||||
std::uint32_t size=write?static_cast<std::uint32_t>(json.size()):0;
|
||||
if (!Bytes(pipe,&size,4,write,stop,deadline) || !size || size>kMaxMessage) return false;
|
||||
if (!write) json.resize(size);
|
||||
return Bytes(pipe,json.data(),size,write,stop,deadline);
|
||||
}
|
||||
}
|
||||
std::wstring PipeName() {
|
||||
DWORD session=0; ProcessIdToSessionId(GetCurrentProcessId(),&session);
|
||||
auto sid=UserSid(); if (sid.empty()) return {};
|
||||
return L"\\\\.\\pipe\\TTDownloader.Browser."+sid+L"."+std::to_wstring(session);
|
||||
}
|
||||
std::string Exchange(const std::string& input,const std::wstring& name) {
|
||||
if (name.empty()) return Serialize(Reply("connection_failed","无法确定当前用户"));
|
||||
Handle pipe(CreateFileW(name.c_str(),GENERIC_READ|GENERIC_WRITE,0,nullptr,OPEN_EXISTING,
|
||||
FILE_FLAG_OVERLAPPED|SECURITY_SQOS_PRESENT|SECURITY_IDENTIFICATION,nullptr),&CloseHandle);
|
||||
if (pipe.get()==INVALID_HANDLE_VALUE && GetLastError()==ERROR_PIPE_BUSY) {
|
||||
WaitNamedPipeW(name.c_str(),1500);
|
||||
pipe.reset(CreateFileW(name.c_str(),GENERIC_READ|GENERIC_WRITE,0,nullptr,OPEN_EXISTING,
|
||||
FILE_FLAG_OVERLAPPED|SECURITY_SQOS_PRESENT|SECURITY_IDENTIFICATION,nullptr));
|
||||
}
|
||||
if (pipe.get()==INVALID_HANDLE_VALUE) {
|
||||
DWORD error=GetLastError(); pipe.release();
|
||||
return Serialize(Reply(error==ERROR_FILE_NOT_FOUND?"client_not_running":"connection_failed",
|
||||
error==ERROR_FILE_NOT_FOUND?"桌面客户端未运行,请先启动 TTDownloader":"桌面客户端繁忙或连接失败"));
|
||||
}
|
||||
ULONGLONG deadline=GetTickCount64()+28000;
|
||||
auto json=input;
|
||||
if (!Frame(pipe.get(),json,true,nullptr,deadline) || !Frame(pipe.get(),json,false,nullptr,deadline))
|
||||
return Serialize(Reply("connection_failed","桌面通信中断或超时,请检查桌面任务列表"));
|
||||
return json;
|
||||
}
|
||||
PipeServer::PipeServer():stop_(CreateEventW(nullptr,TRUE,FALSE,nullptr)) {}
|
||||
PipeServer::~PipeServer() { Stop(); if (stop_) CloseHandle(stop_); }
|
||||
void PipeServer::Start(Handler handler,std::wstring name) {
|
||||
if (worker_.joinable() || !stop_ || name.empty()) return;
|
||||
ResetEvent(stop_); worker_=std::thread(&PipeServer::Run,this,std::move(handler),std::move(name));
|
||||
}
|
||||
void PipeServer::Stop() { if (stop_) SetEvent(stop_); if (worker_.joinable()) worker_.join(); }
|
||||
void PipeServer::Run(Handler handler,const std::wstring& name) {
|
||||
auto sid=UserSid(); if (sid.empty()) return;
|
||||
PSECURITY_DESCRIPTOR descriptor=nullptr;
|
||||
auto sddl=L"D:P(A;;GA;;;SY)(A;;GA;;;"+sid+L")";
|
||||
if (!ConvertStringSecurityDescriptorToSecurityDescriptorW(sddl.c_str(),SDDL_REVISION_1,&descriptor,nullptr)) return;
|
||||
SECURITY_ATTRIBUTES security{sizeof(security),descriptor,FALSE};
|
||||
Handle pipe(CreateNamedPipeW(name.c_str(),PIPE_ACCESS_DUPLEX|FILE_FLAG_OVERLAPPED|FILE_FLAG_FIRST_PIPE_INSTANCE,
|
||||
PIPE_TYPE_BYTE|PIPE_READMODE_BYTE|PIPE_WAIT|PIPE_REJECT_REMOTE_CLIENTS,1,kMaxMessage+4,kMaxMessage+4,1000,&security),&CloseHandle);
|
||||
if (pipe.get()==INVALID_HANDLE_VALUE) { pipe.release(); LocalFree(descriptor); return; }
|
||||
while (WaitForSingleObject(stop_,0)!=WAIT_OBJECT_0) {
|
||||
Handle event(CreateEventW(nullptr,TRUE,FALSE,nullptr),&CloseHandle);
|
||||
if (!event) break;
|
||||
OVERLAPPED operation{}; operation.hEvent=event.get(); DWORD done=0;
|
||||
BOOL connected=ConnectNamedPipe(pipe.get(),&operation);
|
||||
DWORD error=connected?ERROR_SUCCESS:GetLastError();
|
||||
if (!connected && error==ERROR_IO_PENDING) connected=Complete(pipe.get(),operation,stop_,GetTickCount64()+3600000,done);
|
||||
else if (error==ERROR_PIPE_CONNECTED) connected=TRUE;
|
||||
if (connected && WaitForSingleObject(stop_,0)!=WAIT_OBJECT_0) {
|
||||
std::string json;
|
||||
if (Frame(pipe.get(),json,false,stop_,GetTickCount64()+5000)) {
|
||||
auto response=handler(json,stop_);
|
||||
if (Frame(pipe.get(),response,true,stop_,GetTickCount64()+5000)) {
|
||||
// Let the client consume the response and close before disconnect discards buffers.
|
||||
char closed=0; Bytes(pipe.get(),&closed,1,false,stop_,GetTickCount64()+2000);
|
||||
}
|
||||
}
|
||||
}
|
||||
DisconnectNamedPipe(pipe.get());
|
||||
}
|
||||
LocalFree(descriptor);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
#pragma once
|
||||
#include <windows.h>
|
||||
#include <atomic>
|
||||
#include <functional>
|
||||
#include <string>
|
||||
#include <thread>
|
||||
namespace browser_bridge {
|
||||
std::wstring PipeName();
|
||||
std::string Exchange(const std::string& json,const std::wstring& name=PipeName());
|
||||
class PipeServer {
|
||||
public:
|
||||
using Handler=std::function<std::string(const std::string&,HANDLE)>;
|
||||
PipeServer();
|
||||
~PipeServer();
|
||||
void Start(Handler handler,std::wstring name=PipeName());
|
||||
void Stop();
|
||||
private:
|
||||
void Run(Handler,const std::wstring&);
|
||||
HANDLE stop_=nullptr;
|
||||
std::thread worker_;
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,122 @@
|
||||
#include <windows.h>
|
||||
#include "protocol.h"
|
||||
#include <cctype>
|
||||
#include <set>
|
||||
namespace browser_bridge {
|
||||
namespace {
|
||||
class Parser {
|
||||
public:
|
||||
explicit Parser(const std::string& s):s_(s) {}
|
||||
bool Object(Message& fields) {
|
||||
Skip(); if (!Take('{')) return false; Skip();
|
||||
if (Take('}')) { Skip(); return at_==s_.size(); }
|
||||
do {
|
||||
std::string key,value;
|
||||
if (!String(key)) return false; Skip();
|
||||
if (!Take(':')) return false; Skip();
|
||||
if (!String(value) || fields.size()>=16 || !fields.emplace(key,value).second) return false;
|
||||
Skip(); if (Take('}')) { Skip(); return at_==s_.size(); }
|
||||
if (!Take(',')) return false; Skip();
|
||||
} while (at_<s_.size());
|
||||
return false;
|
||||
}
|
||||
private:
|
||||
void Skip() { while (at_<s_.size() && (s_[at_]==' ' || s_[at_]=='\r' || s_[at_]=='\n' || s_[at_]=='\t')) ++at_; }
|
||||
bool Take(char c) { if (at_>=s_.size() || s_[at_]!=c) return false; ++at_; return true; }
|
||||
bool Hex(unsigned& value) {
|
||||
value=0;
|
||||
for (int i=0;i<4;++i) {
|
||||
if (at_>=s_.size()) return false;
|
||||
char c=s_[at_++]; unsigned d;
|
||||
if (c>='0' && c<='9') d=c-'0'; else if (c>='a' && c<='f') d=c-'a'+10;
|
||||
else if (c>='A' && c<='F') d=c-'A'+10; else return false;
|
||||
value=value*16+d;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
bool String(std::string& value) {
|
||||
if (!Take('"')) return false;
|
||||
while (at_<s_.size()) {
|
||||
unsigned char c=s_[at_++];
|
||||
if (c=='"') return value.empty() || MultiByteToWideChar(CP_UTF8,MB_ERR_INVALID_CHARS,value.data(),static_cast<int>(value.size()),nullptr,0)>0;
|
||||
if (c<32) return false;
|
||||
if (c!='\\') { value.push_back(c); continue; }
|
||||
if (at_>=s_.size()) return false; c=s_[at_++];
|
||||
if (c=='"' || c=='\\' || c=='/') value.push_back(c);
|
||||
else if (c=='b') value+='\b'; else if (c=='f') value+='\f';
|
||||
else if (c=='n') value+='\n'; else if (c=='r') value+='\r'; else if (c=='t') value+='\t';
|
||||
else if (c=='u') {
|
||||
unsigned first,second; if (!Hex(first)) return false;
|
||||
wchar_t wide[2]={static_cast<wchar_t>(first),0}; int count=1;
|
||||
if (first>=0xD800 && first<=0xDBFF) {
|
||||
if (!Take('\\') || !Take('u') || !Hex(second) || second<0xDC00 || second>0xDFFF) return false;
|
||||
wide[1]=static_cast<wchar_t>(second); count=2;
|
||||
} else if (first>=0xDC00 && first<=0xDFFF) return false;
|
||||
char bytes[8]{}; int size=WideCharToMultiByte(CP_UTF8,WC_ERR_INVALID_CHARS,wide,count,bytes,8,nullptr,nullptr);
|
||||
if (!size) return false; value.append(bytes,size);
|
||||
} else return false;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
const std::string& s_; size_t at_=0;
|
||||
};
|
||||
std::string Quote(const std::string& text) {
|
||||
constexpr char hex[]="0123456789abcdef"; std::string result="\"";
|
||||
for (unsigned char c:text) {
|
||||
if (c=='"' || c=='\\') { result+='\\'; result+=c; }
|
||||
else if (c<32) { result+="\\u00"; result+=hex[c>>4]; result+=hex[c&15]; }
|
||||
else result+=c;
|
||||
}
|
||||
return result+'"';
|
||||
}
|
||||
bool HttpUrl(const std::string& text) {
|
||||
size_t start=text.rfind("http://",0)==0?7:text.rfind("https://",0)==0?8:0;
|
||||
if (!start || text.size()>16384 || text.find_first_of("\r\n\t ")!=std::string::npos) return false;
|
||||
auto end=text.find_first_of("/?#",start);
|
||||
auto authority=text.substr(start,end==std::string::npos?end:end-start);
|
||||
return !authority.empty() && authority.find('@')==std::string::npos;
|
||||
}
|
||||
}
|
||||
bool Parse(const std::string& json,Message& fields,std::string& error) {
|
||||
fields.clear();
|
||||
if (json.empty() || json.size()>kMaxMessage || !Parser(json).Object(fields)) { error="消息必须是有效的 UTF-8 字符串字段对象"; return false; }
|
||||
return true;
|
||||
}
|
||||
std::string Serialize(const Message& fields) {
|
||||
std::string json="{";
|
||||
for (const auto& [key,value]:fields) { if (json.size()>1) json+=','; json+=Quote(key)+':'+Quote(value); }
|
||||
return json+'}';
|
||||
}
|
||||
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"};
|
||||
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; }
|
||||
}
|
||||
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"))
|
||||
|| (!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;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
bool ReadFrame(std::istream& input,std::string& json) {
|
||||
unsigned char b[4]; if (!input.read(reinterpret_cast<char*>(b),4)) return false;
|
||||
std::uint32_t n=b[0]|(static_cast<std::uint32_t>(b[1])<<8)|(static_cast<std::uint32_t>(b[2])<<16)|(static_cast<std::uint32_t>(b[3])<<24);
|
||||
if (!n || n>kMaxMessage) return false;
|
||||
json.resize(n); return static_cast<bool>(input.read(json.data(),n));
|
||||
}
|
||||
bool WriteFrame(std::ostream& output,const std::string& json) {
|
||||
if (json.empty() || json.size()>kMaxMessage) return false;
|
||||
auto n=static_cast<std::uint32_t>(json.size()); unsigned char b[4]={static_cast<unsigned char>(n),static_cast<unsigned char>(n>>8),static_cast<unsigned char>(n>>16),static_cast<unsigned char>(n>>24)};
|
||||
output.write(reinterpret_cast<char*>(b),4); output.write(json.data(),json.size()); output.flush(); return static_cast<bool>(output);
|
||||
}
|
||||
Message Reply(const std::string& status,const std::string& message,const std::string& id,const std::string& task) {
|
||||
return {{"status",status},{"message",message},{"request_id",id},{"task_id",task}};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
#pragma once
|
||||
#include <cstdint>
|
||||
#include <istream>
|
||||
#include <ostream>
|
||||
#include <map>
|
||||
#include <string>
|
||||
namespace browser_bridge {
|
||||
inline constexpr std::uint32_t kMaxMessage=64*1024;
|
||||
using Message=std::map<std::string,std::string>;
|
||||
bool Parse(const std::string&,Message&,std::string& error);
|
||||
std::string Serialize(const Message&);
|
||||
bool Validate(const Message&,std::string& error);
|
||||
std::string Get(const Message&,const std::string& key);
|
||||
bool ReadFrame(std::istream&,std::string&);
|
||||
bool WriteFrame(std::ostream&,const std::string&);
|
||||
Message Reply(const std::string& status,const std::string& message,const std::string& request_id="",const std::string& task_id="");
|
||||
}
|
||||
@@ -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>
|
||||
@@ -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');
|
||||
});
|
||||
@@ -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')
|
||||
@@ -0,0 +1,3 @@
|
||||
@echo off
|
||||
"%~dp0..\client\bin\ttdownloader_native_host.exe" --unregister chrome
|
||||
exit /b %ERRORLEVEL%
|
||||
Reference in new issue
Block a user