diff --git a/.gitignore b/.gitignore
index 119ce3e..b786d90 100644
--- a/.gitignore
+++ b/.gitignore
@@ -27,3 +27,7 @@ Desktop.ini
# TTUI build output
ui/ttui/lib/
ui/ttui/obj/
+
+# Browser host intermediates
+browser/native/obj/
+browser/tests/obj/
diff --git a/AGENTS.md b/AGENTS.md
index 779c0d9..44494e1 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -34,6 +34,16 @@
- 桌面端未运行、通信失败或任务重复时,应向用户提供明确状态,不得静默丢任务。
- 不默认拦截浏览器全部下载;自动接管、站点规则和过滤策略应可配置。
+## 浏览器插件当前实现
+
+- `browser/chrome/` 为 Chrome/Edge Manifest V3 扩展,包含链接右键发送、手动地址输入、默认关闭的自动接管,以及站点/文件类型过滤。
+- `browser/native/` 为 C++ Native Messaging Host,使用固定扩展公钥对应的 allowed_origins;不得向 stdout 输出协议帧以外的日志。消息为最多 64KiB 的 UTF-8 字符串字段对象。
+- `browser/shared/` 为受当前用户 ACL 和会话隔离保护的本地命名管道。IPC 在独立线程执行,任务校验和 SQLite 入库仍由下载引擎线程完成。
+- 自动接管仅处理观察到的 HTTP/HTTPS GET 下载;先记录恢复状态、暂停浏览器、等待任务入库确认,再取消浏览器下载。重复、离线、通信失败时恢复浏览器,后台重启须恢复未完成交接,不能把恢复状态只放在内存中。
+- 浏览器上下文仅包含 Referer、User-Agent 和文件名提示;首版不传 Cookie、认证信息、POST 请求体或 blob/data 数据。Referer 和 User-Agent 通过 TaskStore 保存,恢复下载仍须沿用,所有请求头拒绝控制字符。
+- 请求编号随任务保存,重试相同请求编号不得重复创建任务;明确区分 accepted、duplicate、rejected、client_not_running、client_not_ready 和通信失败。
+- Host 注册必须由用户执行 `browser/register-host.cmd`(当前用户注册,无需管理员);编译、测试不能自动安装扩展或修改用户浏览器配置。新功能需同时更新本地 IPC/stdio、恢复状态机和 HTTP 上下文回归测试。
+
## HTTP 传输层边界
- `client/src/http_transport.h` 定义不含 Windows/WinHTTP 原生句柄的请求、响应和同步流接口;传输层不依赖 TaskInfo、TaskStore、窗口或下载任务命令。
diff --git a/TTDownloader.sln b/TTDownloader.sln
index 552f8df..75122d0 100644
--- a/TTDownloader.sln
+++ b/TTDownloader.sln
@@ -6,6 +6,8 @@ Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "ttdownloader", "client\ttdo
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "ttui", "ui\ttui\ttui.vcxproj", "{19F8F655-C0F5-4AD9-B999-58D23F95AB43}"
EndProject
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "native_host", "browser\native\native_host.vcxproj", "{F8C0CDE7-9F20-4D81-A472-73BA1F151505}"
+EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|x64 = Debug|x64
@@ -20,6 +22,10 @@ Global
{19F8F655-C0F5-4AD9-B999-58D23F95AB43}.Debug|x64.Build.0 = Debug|x64
{19F8F655-C0F5-4AD9-B999-58D23F95AB43}.Release|x64.ActiveCfg = Release|x64
{19F8F655-C0F5-4AD9-B999-58D23F95AB43}.Release|x64.Build.0 = Release|x64
+ {F8C0CDE7-9F20-4D81-A472-73BA1F151505}.Debug|x64.ActiveCfg = Debug|x64
+ {F8C0CDE7-9F20-4D81-A472-73BA1F151505}.Debug|x64.Build.0 = Debug|x64
+ {F8C0CDE7-9F20-4D81-A472-73BA1F151505}.Release|x64.ActiveCfg = Release|x64
+ {F8C0CDE7-9F20-4D81-A472-73BA1F151505}.Release|x64.Build.0 = Release|x64
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
diff --git a/browser/README.md b/browser/README.md
new file mode 100644
index 0000000..68dcb19
--- /dev/null
+++ b/browser/README.md
@@ -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)。
diff --git a/browser/chrome/background.js b/browser/chrome/background.js
new file mode 100644
index 0000000..74b49f3
--- /dev/null
+++ b/browser/chrome/background.js
@@ -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();
diff --git a/browser/chrome/icon.png b/browser/chrome/icon.png
new file mode 100644
index 0000000..3c6a8f6
Binary files /dev/null and b/browser/chrome/icon.png differ
diff --git a/browser/chrome/logic.mjs b/browser/chrome/logic.mjs
new file mode 100644
index 0000000..2031a8f
--- /dev/null
+++ b/browser/chrome/logic.mjs
@@ -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;
+}
diff --git a/browser/chrome/manifest.json b/browser/chrome/manifest.json
new file mode 100644
index 0000000..ddcaa05
--- /dev/null
+++ b/browser/chrome/manifest.json
@@ -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"
+ }
+}
diff --git a/browser/chrome/popup.css b/browser/chrome/popup.css
new file mode 100644
index 0000000..4a59d31
--- /dev/null
+++ b/browser/chrome/popup.css
@@ -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}
diff --git a/browser/chrome/popup.html b/browser/chrome/popup.html
new file mode 100644
index 0000000..5e740b6
--- /dev/null
+++ b/browser/chrome/popup.html
@@ -0,0 +1,5 @@
+
TTDownloader
+TTDownloader
正在读取状态…
+
+
+也可右键点击链接发送。自动接管默认关闭;失败会恢复浏览器下载。首版不接管 POST、blob、登录 Cookie 或无法确认方法的下载。
diff --git a/browser/chrome/popup.js b/browser/chrome/popup.js
new file mode 100644
index 0000000..9b3a979
--- /dev/null
+++ b/browser/chrome/popup.js
@@ -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}); }
+};
diff --git a/browser/native/main.cpp b/browser/native/main.cpp
new file mode 100644
index 0000000..3b4fa51
--- /dev/null
+++ b/browser/native/main.cpp
@@ -0,0 +1,73 @@
+#include "../shared/protocol.h"
+#include "../shared/pipe.h"
+#include "../shared/identity.h"
+#include
+#include
+#include
+#include
+namespace {
+std::string Utf8(const std::wstring& value) {
+ int size=WideCharToMultiByte(CP_UTF8,0,value.data(),static_cast(value.size()),nullptr,0,nullptr,nullptr);
+ std::string text(size,0); WideCharToMultiByte(CP_UTF8,0,value.data(),static_cast(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 executable(32768),local(32768);
+ DWORD n=GetModuleFileNameW(nullptr,executable.data(),static_cast(executable.size()));
+ DWORD m=GetEnvironmentVariableW(L"LOCALAPPDATA",local.data(),static_cast(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(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(manifest.c_str()),static_cast((manifest.size()+1)*sizeof(wchar_t)));
+ RegCloseKey(handle); if (status!=ERROR_SUCCESS) return 1;
+ }
+ }
+ std::cout<<(remove?"Unregistered":"Registered")<<" TTDownloader Native Messaging Host for "<=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;
+}
diff --git a/browser/native/native_host.vcxproj b/browser/native/native_host.vcxproj
new file mode 100644
index 0000000..09720bd
--- /dev/null
+++ b/browser/native/native_host.vcxproj
@@ -0,0 +1,24 @@
+
+
+
+ Debugx64
+ Releasex64
+
+ {F8C0CDE7-9F20-4D81-A472-73BA1F151505}false
+
+ Applicationv143Unicode
+
+ $(ProjectDir)..\..\client\bin\$(ProjectDir)obj\$(Configuration)\ttdownloader_native_hostttdownloader_native_host_d
+
+
+ stdcpp20/utf-8 %(AdditionalOptions)Sync
+ NOMINMAX;UNICODE;_UNICODE;_WIN32_WINNT=0x0601;WINVER=0x0601;%(PreprocessorDefinitions)
+ MultiThreadedDebug
+ MultiThreaded
+
+ Console6.01
+
+
+
+
+
diff --git a/browser/package.json b/browser/package.json
new file mode 100644
index 0000000..f845285
--- /dev/null
+++ b/browser/package.json
@@ -0,0 +1 @@
+{"private":true,"type":"module"}
diff --git a/browser/register-host.cmd b/browser/register-host.cmd
new file mode 100644
index 0000000..4107e09
--- /dev/null
+++ b/browser/register-host.cmd
@@ -0,0 +1,3 @@
+@echo off
+"%~dp0..\client\bin\ttdownloader_native_host.exe" --register chrome
+exit /b %ERRORLEVEL%
diff --git a/browser/shared/identity.h b/browser/shared/identity.h
new file mode 100644
index 0000000..b6989dc
--- /dev/null
+++ b/browser/shared/identity.h
@@ -0,0 +1,5 @@
+#pragma once
+namespace browser_bridge {
+inline constexpr char kExtensionOrigin[]="chrome-extension://mlidghkaimgommidibnmcflafblbhcdb/";
+inline constexpr char kHostName[]="com.ttstd.ttdownloader";
+}
diff --git a/browser/shared/pipe.cpp b/browser/shared/pipe.cpp
new file mode 100644
index 0000000..f9349f8
--- /dev/null
+++ b/browser/shared/pipe.cpp
@@ -0,0 +1,113 @@
+#include "pipe.h"
+#include "protocol.h"
+#include
+#include
+#include
+#include
+#include
+#pragma comment(lib,"advapi32.lib")
+namespace browser_bridge {
+namespace {
+using Handle=std::unique_ptr;
+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 buffer(size);
+ if (!size || !GetTokenInformation(token.get(),TokenUser,buffer.data(),size,&size)) return {};
+ LPWSTR sid=nullptr;
+ if (!ConvertSidToStringSidW(reinterpret_cast(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(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(data); DWORD total=0;
+ while (total(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);
+}
+}
diff --git a/browser/shared/pipe.h b/browser/shared/pipe.h
new file mode 100644
index 0000000..08ec0bb
--- /dev/null
+++ b/browser/shared/pipe.h
@@ -0,0 +1,22 @@
+#pragma once
+#include
+#include
+#include
+#include
+#include
+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;
+ 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_;
+};
+}
diff --git a/browser/shared/protocol.cpp b/browser/shared/protocol.cpp
new file mode 100644
index 0000000..d62a489
--- /dev/null
+++ b/browser/shared/protocol.cpp
@@ -0,0 +1,122 @@
+#include
+#include "protocol.h"
+#include
+#include
+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() || 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_(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(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(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 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(b),4)) return false;
+ std::uint32_t n=b[0]|(static_cast(b[1])<<8)|(static_cast(b[2])<<16)|(static_cast(b[3])<<24);
+ if (!n || n>kMaxMessage) return false;
+ json.resize(n); return static_cast(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(json.size()); unsigned char b[4]={static_cast(n),static_cast(n>>8),static_cast(n>>16),static_cast(n>>24)};
+ output.write(reinterpret_cast(b),4); output.write(json.data(),json.size()); output.flush(); return static_cast(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}};
+}
+}
diff --git a/browser/shared/protocol.h b/browser/shared/protocol.h
new file mode 100644
index 0000000..068b53e
--- /dev/null
+++ b/browser/shared/protocol.h
@@ -0,0 +1,17 @@
+#pragma once
+#include
+#include
+#include
+#include