diff --git a/plugins/win-context-menu/.gitignore b/plugins/win-context-menu/.gitignore new file mode 100644 index 000000000..fc5c6beae --- /dev/null +++ b/plugins/win-context-menu/.gitignore @@ -0,0 +1,4 @@ +node_modules/ +*.log +.DS_Store +Thumbs.db diff --git a/plugins/win-context-menu/CHANGELOG.md b/plugins/win-context-menu/CHANGELOG.md new file mode 100644 index 000000000..87d2650ed --- /dev/null +++ b/plugins/win-context-menu/CHANGELOG.md @@ -0,0 +1,9 @@ +# 更新日志 + +## 1.0.0 - 2026-11-27 + +### Added +- 支持扫描与管理 Windows 10 / 11 四大场景右键菜单(文件夹空白处、文件、文件夹、桌面空白处),覆盖 `shell` 项、`AllFilesystemObjects`、`shellex` COM 扩展与 Win11 现代 `AppX/Sparse Package` 扩展。 +- 支持通过 Win32 API 解析本地化中文菜单名、提取真实程序小图标,并按贴近系统真实的顺序排列。 +- 支持默认独立任务栏窗口打开、一次 UAC 常驻提权会话(零蓝框闪烁、15 分钟空闲自动退出)以及前端毫秒级局部刷新。 +- 支持修改前自动备份 `.reg` 与历史状态,并提供「一键还原全部修改」与「一键重启资源管理器」功能。 diff --git a/plugins/win-context-menu/README.md b/plugins/win-context-menu/README.md new file mode 100644 index 000000000..fbc1fb4c3 --- /dev/null +++ b/plugins/win-context-menu/README.md @@ -0,0 +1,31 @@ +# Windows 右键菜单管理 (`win-context-menu`) + +> 作者:Pizalo +> 适用平台:Windows 10 / Windows 11 + +一款面向 ZTools 的无损 Windows 右键菜单管理工具,支持可视化查看、停用、启用及一键还原系统右键菜单项。 + +## 核心特性 + +- **全场景覆盖**:支持管理 **文件夹空白处**(`Directory\Background`)、**文件**(`*` + `AllFilesystemObjects`)、**文件夹**(`Directory` + `AllFilesystemObjects`)、**桌面空白处**(`DesktopBackground`)四大场景。 +- **全面兼容传统项与 Win11 现代扩展**:同时识别传统 `shell` 项、`shellex` COM 扩展以及 Windows 11 现代 AppX / Sparse Package 右键扩展(如 QQ、火绒、PowerToys、Notepad++、压缩软件等);在 Windows 10 上自动跳过 Win11 AppX 扫描以加速启动。 +- **真实图标与系统排序**:通过 Win32 API 解析本地化菜单名称并提取真实程序小图标,按接近 Windows 资源管理器的真实顺序排列。 +- **独立窗口与一次 UAC**:默认以独立任务栏窗口打开,不因切出验收或弹窗而自动关闭;采用常驻本地提权会话(仅监听 `127.0.0.1` 随机端口 + 随机 Token + 15 分钟空闲自动退出),一次授权后全程免重复弹窗,单次开关毫秒级生效。 +- **无损修改与一键还原**: + - 传统 `shell` 项使用微软原生 `LegacyDisable` 值停用,不删除原软件任何配置; + - COM 扩展与 Win11 现代扩展使用 `HKCU\Software\Microsoft\Windows\CurrentVersion\Shell Extensions\Blocked` 拦截(免管理员权限,重启资源管理器即生效); + - 每次修改前自动备份 `.reg` 快照与原始状态至 `~/.ztools/plugin-backups/win-context-menu/`,随时支持 **一键还原全部修改**。 + +## 触发指令 + +在 ZTools 搜索框中输入以下任一关键词即可唤起: +- `右键菜单` +- `右键管理` +- `context menu` +- `youjian` +- `menu` + +## 权限说明(UAC) + +- **免管理员权限**:`HKCU` 下的 `shell` 项,以及所有 `shellex` COM 扩展与 Win11 现代扩展的停用/启用。 +- **需要管理员权限**:`HKLM` 下的全局 `shell` 项(插件启动时自动一次性申请 UAC,也可随时取消以普通模式运行)。 diff --git a/plugins/win-context-menu/app.js b/plugins/win-context-menu/app.js new file mode 100644 index 000000000..674511edb --- /dev/null +++ b/plugins/win-context-menu/app.js @@ -0,0 +1,481 @@ +// Windows 右键菜单管理前端交互逻辑(支持一次 UAC 常驻提权 + 毫秒级局部更新) +(function () { + const state = { + scope: "dir-bg", + keyword: "", + status: "all", + items: [], + historyCount: 0, + busy: false, + adminActive: false, + autoElevAttempted: false, + }; + + const els = { + scopeTabs: document.getElementById("scopeTabs"), + searchInput: document.getElementById("searchInput"), + statusFilter: document.getElementById("statusFilter"), + adminSessionBtn: document.getElementById("adminSessionBtn"), + refreshBtn: document.getElementById("refreshBtn"), + explorerBanner: document.getElementById("explorerBanner"), + bannerRestartBtn: document.getElementById("bannerRestartBtn"), + loadingBox: document.getElementById("loadingBox"), + emptyBox: document.getElementById("emptyBox"), + itemList: document.getElementById("itemList"), + statsText: document.getElementById("statsText"), + openBackupBtn: document.getElementById("openBackupBtn"), + restartExplorerBtn: document.getElementById("restartExplorerBtn"), + restoreAllBtn: document.getElementById("restoreAllBtn"), + toast: document.getElementById("toast"), + }; + + let toastTimer = null; + function showToast(msg, duration = 2400) { + els.toast.textContent = msg; + els.toast.classList.remove("hidden"); + clearTimeout(toastTimer); + toastTimer = setTimeout(() => { + els.toast.classList.add("hidden"); + }, duration); + } + + function applyTheme(isDark) { + document.documentElement.setAttribute("data-theme", isDark ? "dark" : "light"); + } + + function updateAdminButton() { + if (state.adminActive) { + els.adminSessionBtn.textContent = "管理员已授权"; + els.adminSessionBtn.className = "btn btn-ok"; + els.adminSessionBtn.title = "常驻管理员会话已激活(15 分钟空闲自动退出),切换 HKLM 项免重复 UAC 弹窗;点击可手动退出会话"; + } else { + els.adminSessionBtn.textContent = "获取管理员权限"; + els.adminSessionBtn.className = "btn btn-secondary"; + els.adminSessionBtn.title = "一次性获取管理员权限,后续切换 HKLM 菜单项免重复 UAC 弹窗"; + } + } + + const isStandalone = new URLSearchParams(window.location.search).get("standalone") === "1"; + let standaloneWin = null; + + /** + * 配置型插件默认以独立窗口打开(带任务栏图标、失焦/弹 UAC 不自动关闭) + */ + function openInStandaloneWindow() { + if (!window.ztools || typeof window.ztools.createBrowserWindow !== "function") { + return false; + } + + // 若独立窗口已存在且未关闭,直接唤回前台(单例复用) + if (standaloneWin) { + try { + const destroyed = typeof standaloneWin.isDestroyed === "function" ? standaloneWin.isDestroyed() : false; + if (!destroyed) { + if (typeof standaloneWin.show === "function") standaloneWin.show(); + if (typeof standaloneWin.focus === "function") standaloneWin.focus(); + if (typeof window.ztools.hideMainWindow === "function") window.ztools.hideMainWindow(); + return true; + } + } catch (_) {} + standaloneWin = null; + } + + try { + standaloneWin = window.ztools.createBrowserWindow("index.html?standalone=1", { + title: "Windows 右键菜单管理", + width: 880, + height: 640, + minWidth: 680, + minHeight: 480, + show: true, + autoHideMenuBar: true, + webPreferences: { + preload: "preload.js", + devTools: true, + }, + }); + if (typeof window.ztools.hideMainWindow === "function") { + window.ztools.hideMainWindow(); + } + // 在悬浮主窗口保留简洁提示,万一用户手动切回主窗口也能一键唤回独立窗口 + els.loadingBox.innerHTML = + '已在独立窗口中打开「Windows 右键菜单管理」

'; + els.loadingBox.classList.remove("hidden"); + const btn = document.getElementById("reopenStandaloneBtn"); + if (btn) btn.addEventListener("click", () => openInStandaloneWindow()); + return true; + } catch (_) { + standaloneWin = null; + return false; + } + } + + function shouldLaunchStandalone() { + if (isStandalone) return false; + if (!window.ztools || typeof window.ztools.createBrowserWindow !== "function") return false; + try { + if (typeof window.ztools.getWindowType === "function") { + const wt = window.ztools.getWindowType(); + // 如果用户已在 ZTools 中把插件手动分离为独立窗口,就直接在当前窗口运行,不再套娃开新窗 + if (wt && wt !== "main") return false; + } + } catch (_) {} + return true; + } + + function initZToolsBridge() { + if (!window.ztools) return; + try { + if (typeof window.ztools.getThemeInfo === "function") { + const info = window.ztools.getThemeInfo(); + applyTheme(Boolean(info && info.isDark)); + } else if (typeof window.ztools.isDarkColors === "function") { + applyTheme(Boolean(window.ztools.isDarkColors())); + } + if (typeof window.ztools.onThemeChange === "function") { + window.ztools.onThemeChange((info) => { + applyTheme(Boolean(info && info.isDark)); + }); + } + if (!isStandalone && typeof window.ztools.setExpendHeight === "function") { + window.ztools.setExpendHeight(220); + } + if (!isStandalone && typeof window.ztools.onPluginEnter === "function") { + window.ztools.onPluginEnter(() => { + if (shouldLaunchStandalone()) { + openInStandaloneWindow(); + } else { + bootstrap(); + } + }); + } + } catch (_) {} + } + + function getFilteredItems() { + const kw = state.keyword.trim().toLowerCase(); + return state.items.filter((item) => { + if (state.scope !== "all" && item.scopeId !== state.scope) return false; + if (state.status === "enabled" && !item.enabled) return false; + if (state.status === "disabled" && item.enabled) return false; + if (kw) { + const hay = `${item.displayName} ${item.keyName} ${item.regPath} ${item.command || ""}`.toLowerCase(); + if (!hay.includes(kw)) return false; + } + return true; + }); + } + + function escapeHtml(str) { + return String(str || "") + .replace(/&/g, "&") + .replace(//g, ">") + .replace(/"/g, """); + } + + function render() { + updateAdminButton(); + const list = getFilteredItems(); + const enabledCount = list.filter((i) => i.enabled).length; + const disabledCount = list.length - enabledCount; + + els.statsText.textContent = `当前显示 ${list.length} 项(已启用 ${enabledCount} / 已停用 ${disabledCount})`; + els.restoreAllBtn.textContent = `一键还原全部修改 (${state.historyCount})`; + els.restoreAllBtn.disabled = state.busy || state.historyCount === 0; + + if (list.length === 0) { + els.itemList.innerHTML = ""; + els.emptyBox.classList.remove("hidden"); + return; + } + + els.emptyBox.classList.add("hidden"); + els.itemList.innerHTML = list + .map((item) => { + const badges = []; + if (state.scope === "all") { + badges.push(`${escapeHtml(item.scopeLabel)}`); + } + badges.push( + item.subKind === "win11" + ? `Win11现代扩展` + : item.kind === "shellex" + ? `COM扩展` + : `Shell项` + ); + if (item.needsAdmin && !state.adminActive) { + badges.push(`需管理员(UAC)`); + } else if (item.needsAdmin && state.adminActive) { + badges.push(`HKLM · 已授权`); + } else { + badges.push(`免提权`); + } + if (item.isExtended) { + badges.push(`按住Shift显示`); + } + if (item.isSystemHint) { + badges.push(`系统内置`); + } + if (!item.enabled) { + badges.push(`已停用`); + } + + const subLine = item.command + ? `${item.keyName} · ${item.command}` + : `${item.keyName} · ${item.regPath}`; + + const iconHtml = item.iconDataUrl + ? `
` + : `
${item.kind === "shellex" ? "⚙" : "▸"}
`; + + return ` +
+ ${iconHtml} +
+
+ ${escapeHtml(item.displayName)} + ${badges.join("")} +
+
${escapeHtml(subLine)}
+
+ +
+ `; + }) + .join(""); + } + + async function loadItems(silent = false) { + if (!window.ctxMenuApi) { + els.loadingBox.textContent = "未检测到 preload 接口,请在 ZTools 宿主中打开此插件。"; + return; + } + state.busy = true; + if (!silent) { + els.loadingBox.classList.remove("hidden"); + els.emptyBox.classList.add("hidden"); + els.itemList.innerHTML = ""; + } + els.refreshBtn.disabled = true; + + const res = await window.ctxMenuApi.scan(); + state.busy = false; + els.loadingBox.classList.add("hidden"); + els.refreshBtn.disabled = false; + + if (!res || !res.ok) { + els.emptyBox.textContent = `扫描失败:${(res && res.error) || "未知错误"}`; + els.emptyBox.classList.remove("hidden"); + return; + } + + state.items = Array.isArray(res.items) ? res.items : []; + state.historyCount = Number(res.historyCount || 0); + if (res.isAdmin) state.adminActive = true; + render(); + } + + /** + * 启动引导: + * 1. 先检查是否已有存活的常驻管理员会话(有的话直接秒级复用 scan,无需弹 UAC) + * 2. 若未激活且首次进入,自动一次性发起 UAC 申请常驻管理员会话,激活后后续 scan & toggle 均毫秒级完成 + */ + async function bootstrap() { + if (!window.ctxMenuApi) return; + const status = await window.ctxMenuApi.getSessionStatus(); + state.adminActive = Boolean(status && status.active && status.isAdmin); + updateAdminButton(); + + if (state.adminActive) { + // 已有常驻 Worker,直接毫秒级扫描 + await loadItems(state.items.length > 0); + return; + } + + if (!state.autoElevAttempted) { + state.autoElevAttempted = true; + els.loadingBox.textContent = "正在申请一次性管理员权限(激活后全程免重复 UAC 且操作秒级响应)..."; + els.loadingBox.classList.remove("hidden"); + const elev = await window.ctxMenuApi.startElevatedSession(); + if (elev && elev.ok && elev.isAdmin) { + state.adminActive = true; + updateAdminButton(); + showToast("管理员会话已激活,后续切换无需再弹 UAC"); + } else { + showToast("已使用普通模式加载(HKCU/COM 扩展可免提权开关)"); + } + } + + await loadItems(state.items.length > 0); + } + + async function handleAdminBtnClick() { + if (state.busy) return; + if (state.adminActive) { + const ok = window.confirm("确定退出当前常驻管理员会话吗?退出后修改 HKLM 项将重新请求 UAC。"); + if (!ok) return; + await window.ctxMenuApi.stopElevatedSession(); + state.adminActive = false; + render(); + showToast("已退出管理员会话"); + return; + } + + showToast("正在请求一次性管理员授权...", 3000); + const elev = await window.ctxMenuApi.startElevatedSession(); + if (elev && elev.ok && elev.isAdmin) { + state.adminActive = true; + render(); + showToast("管理员会话已激活,后续操作全程免重复 UAC"); + } else { + showToast(`未获取管理员权限:${(elev && elev.error) || "已取消"}`); + } + } + + async function handleToggle(item, targetEnabled, checkboxEl) { + if (state.busy) return; + if (item.isSystemHint && !targetEnabled) { + const ok = window.confirm(`「${item.displayName}」属于系统常用/内置项,确定要停用吗?(随时可一键还原)`); + if (!ok) { + checkboxEl.checked = item.enabled; + return; + } + } + + state.busy = true; + checkboxEl.disabled = true; + + const op = { + id: item.id, + kind: item.kind, + hive: item.hive, + keyName: item.keyName, + displayName: item.displayName, + regPath: item.regPath, + clsid: item.clsid, + currentEnabled: item.enabled, + targetEnabled, + needsAdmin: item.needsAdmin, + }; + + const res = await window.ctxMenuApi.toggleItems([op]); + state.busy = false; + + if (!res || !res.ok) { + checkboxEl.checked = item.enabled; + checkboxEl.disabled = false; + showToast(`操作失败:${(res && res.error) || "未知错误"}`, 3500); + return; + } + + // 毫秒级局部状态更新,无需再花十几秒全量扫描! + if (item.kind === "shellex" && item.clsid) { + // 同 CLSID 的 COM 扩展在多个场景下共享拦截状态,一并同步 + for (const it of state.items) { + if (it.kind === "shellex" && it.clsid === item.clsid) { + it.enabled = targetEnabled; + } + } + } else { + item.enabled = targetEnabled; + } + + if (typeof res.historyCount === "number") { + state.historyCount = res.historyCount; + } + if (item.needsAdmin) { + const st = await window.ctxMenuApi.getSessionStatus(); + state.adminActive = Boolean(st && st.active && st.isAdmin); + } + + if (res.needsExplorerRestart) { + els.explorerBanner.classList.remove("hidden"); + } + render(); + showToast(`已${targetEnabled ? "启用" : "停用"}「${item.displayName}」`); + } + + async function handleRestoreAll() { + if (state.busy || state.historyCount === 0) return; + const ok = window.confirm(`确定要还原所有由本插件修改过的 ${state.historyCount} 项右键菜单吗?`); + if (!ok) return; + + state.busy = true; + render(); + showToast("正在还原修改记录...", 4000); + const res = await window.ctxMenuApi.restoreAll(); + state.busy = false; + + if (!res || !res.ok) { + showToast(`还原失败:${(res && res.error) || "未知错误"}`, 3500); + await loadItems(true); + return; + } + + if (res.needsExplorerRestart) { + els.explorerBanner.classList.remove("hidden"); + } + showToast(`已还原 ${res.restoredCount || 0} 项右键菜单配置`); + await loadItems(true); + } + + async function handleRestartExplorer() { + if (state.busy) return; + showToast("正在重启资源管理器...", 2500); + const res = await window.ctxMenuApi.restartExplorer(); + if (res && res.ok) { + els.explorerBanner.classList.add("hidden"); + showToast("资源管理器已重启,COM 扩展变更已生效"); + } else { + showToast(`重启失败:${(res && res.error) || "未知错误"}`); + } + } + + // 事件绑定 + els.scopeTabs.addEventListener("click", (e) => { + const btn = e.target.closest(".tab"); + if (!btn) return; + els.scopeTabs.querySelectorAll(".tab").forEach((b) => b.classList.remove("active")); + btn.classList.add("active"); + state.scope = btn.dataset.scope; + render(); + }); + + els.searchInput.addEventListener("input", (e) => { + state.keyword = e.target.value; + render(); + }); + + els.statusFilter.addEventListener("change", (e) => { + state.status = e.target.value; + render(); + }); + + els.adminSessionBtn.addEventListener("click", handleAdminBtnClick); + els.refreshBtn.addEventListener("click", () => loadItems(false)); + els.openBackupBtn.addEventListener("click", () => window.ctxMenuApi && window.ctxMenuApi.openBackupDir()); + els.restoreAllBtn.addEventListener("click", handleRestoreAll); + els.restartExplorerBtn.addEventListener("click", handleRestartExplorer); + els.bannerRestartBtn.addEventListener("click", handleRestartExplorer); + + els.itemList.addEventListener("change", (e) => { + const input = e.target.closest(".toggle-input"); + if (!input) return; + const item = state.items.find((i) => i.id === input.dataset.id); + if (!item) return; + handleToggle(item, input.checked, input); + }); + + initZToolsBridge(); + if (shouldLaunchStandalone()) { + // 悬浮主窗口入口:交给 onPluginEnter 或兜底直接拉起独立窗口 + openInStandaloneWindow(); + } else { + // 独立窗口(或已被宿主分离的窗口):正常初始化扫描与一次 UAC 授权 + bootstrap(); + } +})(); diff --git a/plugins/win-context-menu/index.html b/plugins/win-context-menu/index.html new file mode 100644 index 000000000..ae7faf35a --- /dev/null +++ b/plugins/win-context-menu/index.html @@ -0,0 +1,64 @@ + + + + + + Windows 右键菜单管理 + + + +
+ +
+
+ + + + + +
+
+ + + + +
+
+ + + + + +
+
正在扫描系统右键菜单,请稍候...
+ +
+
+ + + +
+ + + + + + + diff --git a/plugins/win-context-menu/logo.png b/plugins/win-context-menu/logo.png new file mode 100644 index 000000000..254e178f1 Binary files /dev/null and b/plugins/win-context-menu/logo.png differ diff --git a/plugins/win-context-menu/plugin.json b/plugins/win-context-menu/plugin.json new file mode 100644 index 000000000..a76d192bb --- /dev/null +++ b/plugins/win-context-menu/plugin.json @@ -0,0 +1,18 @@ +{ + "name": "win-context-menu", + "title": "Windows 右键菜单管理", + "description": "无损扫描、停用与启用 Windows 10/11 右键菜单项(支持传统 Shell 项、COM 扩展与 Win11 现代扩展,改前自动备份、支持一键还原)", + "version": "1.0.0", + "author": "Pizalo", + "platform": ["win32"], + "main": "index.html", + "logo": "logo.png", + "preload": "preload.js", + "features": [ + { + "code": "manage-context-menu", + "explain": "管理 Windows 右键菜单(停用/启用/还原)", + "cmds": ["右键菜单", "右键管理", "context menu", "youjian", "menu"] + } + ] +} diff --git a/plugins/win-context-menu/preload.js b/plugins/win-context-menu/preload.js new file mode 100644 index 000000000..9429f8f95 --- /dev/null +++ b/plugins/win-context-menu/preload.js @@ -0,0 +1,407 @@ +// Windows 右键菜单管理插件 Preload(CommonJS,未压缩,遵循 ZTools 官方规范) +const crypto = require("node:crypto"); +const fs = require("node:fs"); +const http = require("node:http"); +const net = require("node:net"); +const os = require("node:os"); +const path = require("node:path"); +const { execFile } = require("node:child_process"); + +const PLUGIN_DIR = __dirname; +const EMBEDDED_MANAGER_PATH = path.join(PLUGIN_DIR, "scripts", "context-menu-manager.ps1"); +const EMBEDDED_WORKER_PATH = path.join(PLUGIN_DIR, "scripts", "elevated-worker.ps1"); +const SESSION_FILE = path.join(os.tmpdir(), "alltool_ctx_worker_session.json"); + +function resolveBackupDir() { + try { + const repoRoot = path.resolve(PLUGIN_DIR, "..", ".."); + if ( + !PLUGIN_DIR.toLowerCase().includes(".asar") && + fs.existsSync(path.join(repoRoot, "AGENTS.md")) && + fs.existsSync(path.join(repoRoot, "plugins")) + ) { + return path.join(repoRoot, ".local", "backups", "win-context-menu"); + } + } catch (_) {} + return path.join(os.homedir(), ".ztools", "plugin-backups", "win-context-menu"); +} + +const BACKUP_DIR = resolveBackupDir(); + +// 内存中的常驻提权 Worker 会话信息 { port, token, pid, isAdmin } +let workerSession = null; +let elevatingPromise = null; + +/** + * 获取可供外部 powershell.exe 直接执行的真实磁盘脚本路径(兼容 .asar 打包安装) + */ +function ensureRunnableScripts() { + const isInsideAsar = PLUGIN_DIR.toLowerCase().includes(".asar"); + if (!isInsideAsar && fs.existsSync(EMBEDDED_MANAGER_PATH) && fs.existsSync(EMBEDDED_WORKER_PATH)) { + return { + managerPath: EMBEDDED_MANAGER_PATH, + workerPath: EMBEDDED_WORKER_PATH, + }; + } + const runtimeDir = path.join(os.tmpdir(), "alltool-win-context-menu"); + if (!fs.existsSync(runtimeDir)) { + fs.mkdirSync(runtimeDir, { recursive: true }); + } + const copyWithBom = (src, fileName) => { + const dst = path.join(runtimeDir, fileName); + const content = fs.readFileSync(src, "utf8"); + const bom = content.startsWith("\uFEFF") ? content : "\uFEFF" + content; + fs.writeFileSync(dst, bom, "utf8"); + return dst; + }; + return { + managerPath: copyWithBom(EMBEDDED_MANAGER_PATH, "context-menu-manager.ps1"), + workerPath: copyWithBom(EMBEDDED_WORKER_PATH, "elevated-worker.ps1"), + }; +} + +function getFreePort() { + return new Promise((resolve, reject) => { + const srv = net.createServer(); + srv.unref(); + srv.on("error", reject); + srv.listen(0, "127.0.0.1", () => { + const addr = srv.address(); + const port = addr && typeof addr === "object" ? addr.port : 0; + srv.close(() => resolve(port)); + }); + }); +} + +function workerRequest(session, route, method = "GET", bodyObj = null, timeoutMs = 15000) { + return new Promise((resolve) => { + if (!session || !session.port || !session.token) { + resolve({ ok: false, error: "无有效 Worker 会话" }); + return; + } + const bodyText = bodyObj !== null ? JSON.stringify(bodyObj) : ""; + const headers = { + "X-ALLTool-Token": session.token, + }; + if (bodyText) { + headers["Content-Type"] = "application/json; charset=utf-8"; + headers["Content-Length"] = Buffer.byteLength(bodyText, "utf8"); + } + + const req = http.request( + { + hostname: "127.0.0.1", + port: session.port, + path: route, + method, + headers, + timeout: timeoutMs, + }, + (res) => { + const chunks = []; + res.on("data", (c) => chunks.push(c)); + res.on("end", () => { + const raw = Buffer.concat(chunks).toString("utf8").trim(); + try { + resolve(JSON.parse(raw)); + } catch (_) { + resolve({ ok: false, error: `Worker 返回无效响应: ${raw.slice(0, 120)}` }); + } + }); + } + ); + + req.on("timeout", () => { + req.destroy(); + resolve({ ok: false, error: "Worker 请求超时" }); + }); + req.on("error", (err) => { + resolve({ ok: false, error: err.message || String(err) }); + }); + + if (bodyText) req.write(bodyText); + req.end(); + }); +} + +const EXPECTED_WORKER_SCHEMA = 5; + +/** + * 尝试复用已有存活的常驻 Worker 会话(切出插件再切回时免重复 UAC;若检测到旧版 Worker 自动优雅关闭升级) + */ +async function tryReuseExistingSession() { + const checkHealth = async (session) => { + const h = await workerRequest(session, "/health", "GET", null, 1200); + if (h && h.ok) { + if (Number(h.schemaVersion || 1) !== EXPECTED_WORKER_SCHEMA) { + await workerRequest(session, "/shutdown", "POST", {}, 1200); + return null; + } + return { ...session, isAdmin: Boolean(h.isAdmin) }; + } + return null; + }; + + if (workerSession) { + const valid = await checkHealth(workerSession); + if (valid) { + workerSession = valid; + return workerSession; + } + workerSession = null; + } + + try { + if (fs.existsSync(SESSION_FILE)) { + const saved = JSON.parse(fs.readFileSync(SESSION_FILE, "utf8")); + if (saved && saved.port && saved.token) { + const valid = await checkHealth(saved); + if (valid) { + workerSession = valid; + return workerSession; + } + } + } + } catch (_) {} + return null; +} + +/** + * 一次性触发 UAC 启动常驻管理员 Worker(15 分钟空闲自动退出) + */ +async function startElevatedSession() { + const existing = await tryReuseExistingSession(); + if (existing && existing.isAdmin) { + return { ok: true, isAdmin: true, reused: true }; + } + + if (elevatingPromise) return elevatingPromise; + + elevatingPromise = (async () => { + const { managerPath, workerPath } = ensureRunnableScripts(); + const port = await getFreePort(); + const token = crypto.randomBytes(24).toString("hex"); + const stamp = `${Date.now()}_${Math.random().toString(16).slice(2)}`; + const readyFile = path.join(os.tmpdir(), `alltool_ctx_ready_${stamp}.json`); + const launcherPs1 = path.join(os.tmpdir(), `alltool_ctx_launcher_${stamp}.ps1`); + + // 写入纯 ASCII 路径的临时启动器(内容带 UTF-8 BOM),彻底避免中文/空格路径传参转义问题 + const psQuote = (s) => `'${String(s).replace(/'/g, "''")}'`; + const launcherBody = [ + `& ${psQuote(workerPath)} -Port ${port} -Token ${psQuote(token)} -BackupDir ${psQuote(BACKUP_DIR)} -ManagerScriptPath ${psQuote(managerPath)} -ReadyFile ${psQuote(readyFile)}`, + ].join("\r\n"); + fs.writeFileSync(launcherPs1, "\uFEFF" + launcherBody, "utf8"); + + // 把 -WindowStyle Hidden 直接传给 Start-Process 本身(ShellExecuteEx SW_HIDE),彻底消除蓝框闪烁 + const launchCmd = `Start-Process -FilePath 'powershell.exe' -WindowStyle Hidden -ArgumentList @('-NoProfile','-ExecutionPolicy','Bypass','-WindowStyle','Hidden','-File',${psQuote(launcherPs1)}) -Verb RunAs`; + + const launchRes = await new Promise((resolve) => { + execFile( + "powershell.exe", + ["-NoProfile", "-ExecutionPolicy", "Bypass", "-WindowStyle", "Hidden", "-Command", launchCmd], + { encoding: "utf8", windowsHide: true }, + (error, _stdout, stderr) => { + if (error) { + resolve({ ok: false, error: (stderr && stderr.trim()) || error.message }); + } else { + resolve({ ok: true }); + } + } + ); + }); + + if (!launchRes.ok) { + try { if (fs.existsSync(launcherPs1)) fs.unlinkSync(launcherPs1); } catch (_) {} + return { ok: false, isAdmin: false, cancelled: true, error: launchRes.error || "已取消管理员授权" }; + } + + // 轮询等待 Worker 就绪(最长 12 秒) + const deadline = Date.now() + 12000; + while (Date.now() < deadline) { + if (fs.existsSync(readyFile)) { + try { + const info = JSON.parse(fs.readFileSync(readyFile, "utf8")); + try { fs.unlinkSync(readyFile); } catch (_) {} + try { if (fs.existsSync(launcherPs1)) fs.unlinkSync(launcherPs1); } catch (_) {} + if (info && info.ok) { + workerSession = { port, token, pid: info.pid, isAdmin: Boolean(info.isAdmin) }; + try { + fs.writeFileSync(SESSION_FILE, JSON.stringify(workerSession), "utf8"); + } catch (_) {} + return { ok: true, isAdmin: Boolean(info.isAdmin), reused: false }; + } + } catch (_) {} + } + await new Promise((r) => setTimeout(r, 150)); + } + + try { if (fs.existsSync(launcherPs1)) fs.unlinkSync(launcherPs1); } catch (_) {} + return { ok: false, isAdmin: false, error: "等待管理员工作进程启动超时" }; + })(); + + try { + return await elevatingPromise; + } finally { + elevatingPromise = null; + } +} + +/** + * 降级模式:单次直接调用 context-menu-manager.ps1(用于用户取消 UAC 时的只读扫描或 HKCU 免提权操作) + */ +function runFallbackEngine(action, extraArgs = []) { + return new Promise((resolve) => { + let managerPath; + try { + managerPath = ensureRunnableScripts().managerPath; + } catch (err) { + resolve({ ok: false, error: `释放脚本失败: ${err.message || String(err)}` }); + return; + } + + const args = [ + "-NoProfile", + "-ExecutionPolicy", + "Bypass", + "-File", + managerPath, + "-Action", + action, + "-BackupDir", + BACKUP_DIR, + ...extraArgs, + ]; + + execFile( + "powershell.exe", + args, + { encoding: "utf8", windowsHide: true, maxBuffer: 10 * 1024 * 1024 }, + (error, stdout, stderr) => { + const rawOut = (stdout || "").trim(); + if (rawOut) { + const lines = rawOut.split(/\r?\n/).filter((l) => l.trim().length > 0); + const lastLine = lines[lines.length - 1]; + try { + resolve(JSON.parse(lastLine)); + return; + } catch (_) {} + } + resolve({ + ok: false, + error: (stderr && stderr.trim()) || (error && error.message) || "执行 PowerShell 脚本失败", + }); + } + ); + }); +} + +window.ctxMenuApi = { + async getSessionStatus() { + const s = await tryReuseExistingSession(); + return { ok: true, active: Boolean(s), isAdmin: Boolean(s && s.isAdmin) }; + }, + + async startElevatedSession() { + return startElevatedSession(); + }, + + async stopElevatedSession() { + const s = await tryReuseExistingSession(); + if (s) { + await workerRequest(s, "/shutdown", "POST", {}, 2000); + } + workerSession = null; + try { + if (fs.existsSync(SESSION_FILE)) fs.unlinkSync(SESSION_FILE); + } catch (_) {} + return { ok: true }; + }, + + async scan() { + const s = await tryReuseExistingSession(); + if (s) { + // 首次扫描需加载 Win11 AppX 现代右键扩展清单,预留充足超时;后续走 Worker 内存缓存 + const res = await workerRequest(s, "/scan", "GET", null, 35000); + if (res && res.ok) return res; + } + return runFallbackEngine("scan"); + }, + + async toggleItems(operations) { + if (!Array.isArray(operations) || operations.length === 0) { + return { ok: false, error: "操作列表不能为空" }; + } + + // 若包含需管理员权限的项且尚未激活提权会话,先尝试一次性拉起常驻提权 Worker + const needsAdmin = operations.some((op) => Boolean(op.needsAdmin)); + let s = await tryReuseExistingSession(); + if (needsAdmin && (!s || !s.isAdmin)) { + const elev = await startElevatedSession(); + if (elev && elev.ok) { + s = workerSession; + } + } + + if (s && (!needsAdmin || s.isAdmin)) { + const res = await workerRequest(s, "/toggle", "POST", operations, 15000); + if (res && res.ok) return res; + if (res && res.error && !res.error.includes("ECONNREFUSED")) { + return res; + } + } + + // 降级兜底 + const tempFile = path.join( + os.tmpdir(), + `alltool_ctx_payload_${Date.now()}_${Math.random().toString(16).slice(2)}.json` + ); + try { + fs.writeFileSync(tempFile, JSON.stringify(operations), "utf8"); + return await runFallbackEngine("toggle", ["-PayloadFile", tempFile]); + } catch (err) { + return { ok: false, error: err.message || String(err) }; + } finally { + try { + if (fs.existsSync(tempFile)) fs.unlinkSync(tempFile); + } catch (_) {} + } + }, + + async restoreAll() { + let s = await tryReuseExistingSession(); + if (!s || !s.isAdmin) { + const elev = await startElevatedSession(); + if (elev && elev.ok) s = workerSession; + } + if (s) { + const res = await workerRequest(s, "/restore-all", "POST", {}, 20000); + if (res && res.ok) return res; + } + return runFallbackEngine("restore-all"); + }, + + async restartExplorer() { + const s = await tryReuseExistingSession(); + if (s) { + const res = await workerRequest(s, "/restart-explorer", "POST", {}, 10000); + if (res && res.ok) return res; + } + return runFallbackEngine("restart-explorer"); + }, + + getBackupDir() { + return BACKUP_DIR; + }, + + openBackupDir() { + if (!fs.existsSync(BACKUP_DIR)) { + fs.mkdirSync(BACKUP_DIR, { recursive: true }); + } + if (window.ztools && typeof window.ztools.shellOpenPath === "function") { + window.ztools.shellOpenPath(BACKUP_DIR); + return true; + } + execFile("explorer.exe", [BACKUP_DIR], { windowsHide: true }, () => {}); + return true; + }, +}; diff --git a/plugins/win-context-menu/scripts/context-menu-manager.ps1 b/plugins/win-context-menu/scripts/context-menu-manager.ps1 new file mode 100644 index 000000000..2d50ba05c --- /dev/null +++ b/plugins/win-context-menu/scripts/context-menu-manager.ps1 @@ -0,0 +1,941 @@ +#requires -Version 5.1 +<# +.SYNOPSIS + Windows 右键菜单无损扫描、停用/启用与备份回滚引擎 +.DESCRIPTION + - 扫描 HKCU/HKLM 下四大常见场景(文件夹空白处、文件、文件夹、桌面空白处)的 shell 与 shellex 项 + - 使用 Win32 SHLoadIndirectString 解析 @dll,-id 为真实中文菜单名 + - shell 项采用微软原生 LegacyDisable 无损停用;shellex 项采用 HKCU Shell Extensions\Blocked 无损拦截 + - 修改前自动备份注册表快照到 ALLTool\.local\backups\win-context-menu\ +#> +param( + [Parameter(Mandatory = $true)] + [ValidateSet('scan', 'toggle', 'restore-all', 'restart-explorer', 'lib')] + [string]$Action, + + [string]$PayloadFile = '', + [string]$BackupDir = '' +) + +$ErrorActionPreference = 'Stop' +[Console]::OutputEncoding = [System.Text.Encoding]::UTF8 +$OutputEncoding = [System.Text.Encoding]::UTF8 + +# 默认备份目录指向 ALLTool/.local/backups/win-context-menu +if ([string]::IsNullOrWhiteSpace($BackupDir)) { + $repoRoot = Split-Path -Parent (Split-Path -Parent (Split-Path -Parent $PSScriptRoot)) + $BackupDir = Join-Path $repoRoot '.local\backups\win-context-menu' +} + +# 加载 Win32 SHLoadIndirectString 与 ExtractIconEx(用于解析本地化菜单名与提取真实程序小图标) +$win32Type = @' +using System; +using System.Collections.Generic; +using System.Drawing; +using System.Drawing.Drawing2D; +using System.Drawing.Imaging; +using System.IO; +using System.Text; +using System.Runtime.InteropServices; + +public static class ShlwapiHelper { + private static readonly Dictionary IconCache = new Dictionary(StringComparer.OrdinalIgnoreCase); + + [DllImport("shlwapi.dll", BestFitMapping = false, CharSet = CharSet.Unicode, ExactSpelling = true, SetLastError = false, ThrowOnUnmappableChar = true)] + private static extern int SHLoadIndirectString(string pszSource, StringBuilder pszOutBuf, int cchOutBuf, IntPtr ppvReserved); + + [DllImport("shell32.dll", CharSet = CharSet.Unicode)] + private static extern uint ExtractIconEx(string lpszFile, int nIconIndex, IntPtr[] phiconLarge, IntPtr[] phiconSmall, uint nIcons); + + [DllImport("user32.dll", SetLastError = true)] + private static extern bool DestroyIcon(IntPtr hIcon); + + public static string ResolveIndirectString(string input) { + if (string.IsNullOrWhiteSpace(input) || !input.StartsWith("@")) { + return input; + } + try { + var sb = new StringBuilder(512); + int hr = SHLoadIndirectString(input, sb, sb.Capacity, IntPtr.Zero); + if (hr == 0 && sb.Length > 0) { + return sb.ToString(); + } + } catch {} + return input; + } + + private static string ResolveFilePath(string rawPath) { + if (string.IsNullOrWhiteSpace(rawPath)) return ""; + string p = Environment.ExpandEnvironmentVariables(rawPath.Trim().Trim('"').Trim()); + if (p.StartsWith("@")) p = p.Substring(1).Trim().Trim('"'); + if (File.Exists(p)) return p; + // 尝试 System32 目录(如 shell32.dll、imageres.dll、cmd.exe) + if (!p.Contains("\\") && !p.Contains("/")) { + string sys32 = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.System), p); + if (File.Exists(sys32)) return sys32; + string winDir = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Windows), p); + if (File.Exists(winDir)) return winDir; + } + return ""; + } + + private static string ExtractExeFromCommand(string cmd) { + if (string.IsNullOrWhiteSpace(cmd)) return ""; + string s = cmd.Trim(); + if (s.StartsWith("\"")) { + int end = s.IndexOf('"', 1); + if (end > 1) return ResolveFilePath(s.Substring(1, end - 1)); + } + int sp = s.IndexOf(' '); + string first = sp > 0 ? s.Substring(0, sp) : s; + return ResolveFilePath(first); + } + + private static string IconToDataUrl(Icon icon) { + if (icon == null) return ""; + using (var bmp = new Bitmap(24, 24, PixelFormat.Format32bppArgb)) + using (var g = Graphics.FromImage(bmp)) + using (var srcBmp = icon.ToBitmap()) + using (var ms = new MemoryStream()) { + g.InterpolationMode = InterpolationMode.HighQualityBicubic; + g.SmoothingMode = SmoothingMode.HighQuality; + g.Clear(Color.Transparent); + g.DrawImage(srcBmp, 0, 0, 24, 24); + bmp.Save(ms, ImageFormat.Png); + return "data:image/png;base64," + Convert.ToBase64String(ms.ToArray()); + } + } + + public static string ExtractIconDataUrl(string iconSpec, string commandLine) { + string cacheKey = (iconSpec ?? "") + "||" + (commandLine ?? ""); + string cached; + if (IconCache.TryGetValue(cacheKey, out cached)) return cached; + + string result = ""; + try { + string filePath = ""; + int iconIndex = 0; + + if (!string.IsNullOrWhiteSpace(iconSpec)) { + string spec = iconSpec.Trim(); + int comma = spec.LastIndexOf(','); + if (comma > 0) { + int parsedIdx; + if (int.TryParse(spec.Substring(comma + 1).Trim(), out parsedIdx)) { + filePath = ResolveFilePath(spec.Substring(0, comma)); + iconIndex = parsedIdx; + } else { + filePath = ResolveFilePath(spec); + } + } else { + filePath = ResolveFilePath(spec); + } + } + + if (string.IsNullOrEmpty(filePath) && !string.IsNullOrWhiteSpace(commandLine)) { + filePath = ExtractExeFromCommand(commandLine); + iconIndex = 0; + } + + if (!string.IsNullOrEmpty(filePath)) { + if (filePath.EndsWith(".ico", StringComparison.OrdinalIgnoreCase)) { + using (var ico = new Icon(filePath, 24, 24)) { + result = IconToDataUrl(ico); + } + } else { + IntPtr[] smallIcons = new IntPtr[1]; + IntPtr[] largeIcons = new IntPtr[1]; + uint count = ExtractIconEx(filePath, iconIndex, largeIcons, smallIcons, 1); + IntPtr hIcon = smallIcons[0] != IntPtr.Zero ? smallIcons[0] : largeIcons[0]; + if (count > 0 && hIcon != IntPtr.Zero) { + try { + using (var ico = Icon.FromHandle(hIcon)) { + result = IconToDataUrl(ico); + } + } finally { + if (smallIcons[0] != IntPtr.Zero) DestroyIcon(smallIcons[0]); + if (largeIcons[0] != IntPtr.Zero) DestroyIcon(largeIcons[0]); + } + } else if (iconIndex == 0 && filePath.EndsWith(".exe", StringComparison.OrdinalIgnoreCase)) { + using (var ico = Icon.ExtractAssociatedIcon(filePath)) { + result = IconToDataUrl(ico); + } + } + } + } + } catch { + result = ""; + } + + IconCache[cacheKey] = result; + return result; + } +} +'@ + +if (-not ('ShlwapiHelper' -as [type])) { + Add-Type -TypeDefinition $win32Type -Language CSharp -ReferencedAssemblies @('System.Drawing') | Out-Null +} + +function Resolve-DisplayText { + param([string]$Raw) + if ([string]::IsNullOrWhiteSpace($Raw)) { return '' } + $resolved = [ShlwapiHelper]::ResolveIndirectString($Raw.Trim()) + # 去掉菜单快捷键标记(如 &GUI -> GUI),但保留括号提示如 (V) + return ($resolved -replace '&([A-Za-z0-9])', '$1').Trim() +} + +function Test-IsAdmin { + $id = [Security.Principal.WindowsIdentity]::GetCurrent() + $principal = New-Object Security.Principal.WindowsPrincipal($id) + return $principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator) +} + +# 安全反序列化 JSON 数组(规避 PowerShell 5.1 中 @(ConvertFrom-Json) 对多元素数组产生二维嵌套的 Bug) +function ConvertFrom-JsonArray { + param([string]$JsonText) + if ([string]::IsNullOrWhiteSpace($JsonText)) { return @() } + $parsed = ConvertFrom-Json $JsonText + if ($null -eq $parsed) { return @() } + if ($parsed -is [System.Array]) { return $parsed } + return @($parsed) +} + +# 安全序列化数组为 JSON(规避 Windows PowerShell 5.1 中 ConvertTo-Json -InputObject @(...) 报“参数类型不匹配”的已知 Bug) +function ConvertTo-JsonArray { + param( + [AllowEmptyCollection()] + [object[]]$Items, + [int]$Depth = 5 + ) + $arr = @($Items | Where-Object { $null -ne $_ }) + if ($arr.Count -eq 0) { return '[]' } + if ($arr.Count -eq 1) { + return '[' + ($arr[0] | ConvertTo-Json -Depth $Depth) + ']' + } + return ($arr | ConvertTo-Json -Depth $Depth) +} + +function Get-BlockedClsids { + $map = @{} + $paths = @( + @{ Path = 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Shell Extensions\Blocked'; Scope = 'HKCU' }, + @{ Path = 'HKLM:\Software\Microsoft\Windows\CurrentVersion\Shell Extensions\Blocked'; Scope = 'HKLM' } + ) + foreach ($p in $paths) { + if (Test-Path $p.Path) { + $item = Get-Item $p.Path -ErrorAction SilentlyContinue + if ($null -ne $item) { + foreach ($valName in $item.GetValueNames()) { + if ($valName -match '^\{[0-9A-Fa-f-]+\}$') { + $key = $valName.ToUpperInvariant() + if (-not $map.ContainsKey($key)) { + $map[$key] = $p.Scope + } + } + } + } + } + } + return $map +} + +function Resolve-ClsidFriendlyInfo { + param([string]$Clsid) + $info = @{ + name = '' + dll = '' + } + if ([string]::IsNullOrWhiteSpace($Clsid) -or ($Clsid -notmatch '^\{[0-9A-Fa-f-]+\}$')) { + return $info + } + $clsidKey = "Registry::HKEY_CLASSES_ROOT\CLSID\$Clsid" + if (Test-Path $clsidKey) { + $props = Get-ItemProperty $clsidKey -ErrorAction SilentlyContinue + if ($null -ne $props -and -not [string]::IsNullOrWhiteSpace($props.'(default)')) { + $info.name = Resolve-DisplayText $props.'(default)' + } + $inprocKey = Join-Path $clsidKey 'InprocServer32' + if (Test-Path $inprocKey) { + $inprocProps = Get-ItemProperty $inprocKey -ErrorAction SilentlyContinue + if ($null -ne $inprocProps -and -not [string]::IsNullOrWhiteSpace($inprocProps.'(default)')) { + $info.dll = [string]$inprocProps.'(default)' + } + } + } + return $info +} + +# 定义 4 个常用右键场景(文件与文件夹同时聚合 AllFilesystemObjects 通用项,所见即所得) +$Scopes = @( + @{ id = 'dir-bg'; label = '文件夹空白处'; subPaths = @('Directory\Background') }, + @{ id = 'file'; label = '文件'; subPaths = @('*', 'AllFilesystemObjects') }, + @{ id = 'dir'; label = '文件夹'; subPaths = @('Directory', 'AllFilesystemObjects') }, + @{ id = 'desktop-bg'; label = '桌面空白处'; subPaths = @('DesktopBackground') } +) + +$Hives = @( + @{ name = 'HKCU'; psRoot = 'HKCU:\Software\Classes'; regRoot = 'HKEY_CURRENT_USER\Software\Classes'; needsAdmin = $false }, + @{ name = 'HKLM'; psRoot = 'HKLM:\Software\Classes'; regRoot = 'HKEY_LOCAL_MACHINE\Software\Classes'; needsAdmin = $true } +) + +# 常见系统关键扩展,标注提醒防止误关基础功能 +$SystemProtectedKeys = @('New', 'Sharing', 'ModernSharing', 'SendTo', 'CopyAsPathMenu', 'Open Containing Folder Menu', 'EncryptionMenu', 'WorkFolders') + +# 缓存 Win11 现代右键扩展(AppX / Sparse Package)静态元数据,避免常驻 Worker 每次重复调 Get-AppxPackage +if (-not $script:Win11ExtCache) { + $script:Win11ExtCache = $null +} + +function Get-Win11ContextMenuExtensions { + if ($null -ne $script:Win11ExtCache) { + return $script:Win11ExtCache + } + $list = New-Object System.Collections.Generic.List[object] + # Windows 10 (Build < 22000) 无 Win11 现代 FileExplorerContextMenus,直接跳过以大幅提升 Win10 启动速度 + if ([System.Environment]::OSVersion.Version.Build -lt 22000) { + $script:Win11ExtCache = $list + return $script:Win11ExtCache + } + try { + $pkgs = Get-AppxPackage -ErrorAction SilentlyContinue | Where-Object { + $_.InstallLocation -and (Test-Path -LiteralPath (Join-Path $_.InstallLocation 'AppxManifest.xml')) + } + foreach ($pkg in $pkgs) { + $mfPath = Join-Path $pkg.InstallLocation 'AppxManifest.xml' + $raw = '' + try { $raw = [System.IO.File]::ReadAllText($mfPath) } catch { continue } + if ($raw.IndexOf('FileExplorerContextMenus', [StringComparison]::OrdinalIgnoreCase) -lt 0) { + continue + } + + try { + [xml]$xml = $raw + $propDisp = '' + $dispNode = $xml.SelectSingleNode("//*[local-name()='Properties']/*[local-name()='DisplayName']") + if ($null -ne $dispNode -and -not [string]::IsNullOrWhiteSpace($dispNode.InnerText)) { + $propDisp = $dispNode.InnerText.Trim() + } + if ([string]::IsNullOrWhiteSpace($propDisp) -or $propDisp.StartsWith('ms-resource:')) { + $propDisp = $pkg.Name + } + + # 提取包 Logo 或同目录 DLL 图标 + $iconPath = '' + $logoNode = $xml.SelectSingleNode("//*[local-name()='Properties']/*[local-name()='Logo']") + if ($null -ne $logoNode -and -not [string]::IsNullOrWhiteSpace($logoNode.InnerText)) { + $cand = Join-Path $pkg.InstallLocation $logoNode.InnerText.Trim() + if (Test-Path -LiteralPath $cand) { $iconPath = $cand } + } + if ([string]::IsNullOrWhiteSpace($iconPath)) { + $dllCand = Get-ChildItem -LiteralPath $pkg.InstallLocation -Filter '*.dll' -ErrorAction SilentlyContinue | Select-Object -First 1 + if ($null -ne $dllCand) { $iconPath = $dllCand.FullName } + } + + # 读取 PNG Logo 或通过 Win32 提取 DLL 图标 + $iconDataUrl = '' + if ($iconPath -match '\.png$' -and (Test-Path -LiteralPath $iconPath)) { + try { + $bytes = [System.IO.File]::ReadAllBytes($iconPath) + $iconDataUrl = 'data:image/png;base64,' + [Convert]::ToBase64String($bytes) + } catch {} + } elseif (-not [string]::IsNullOrWhiteSpace($iconPath)) { + $iconDataUrl = [ShlwapiHelper]::ExtractIconDataUrl($iconPath, '') + } + + $itemTypes = $xml.SelectNodes("//*[local-name()='FileExplorerContextMenus']//*[local-name()='ItemType']") + foreach ($it in $itemTypes) { + $typeAttr = $it.GetAttribute('Type') + $scopeIds = @() + switch ($typeAttr) { + '*' { $scopeIds = @('file') } + 'Directory' { $scopeIds = @('dir') } + 'Directory\Background' { $scopeIds = @('dir-bg') } + 'DesktopBackground' { $scopeIds = @('desktop-bg') } + default { continue } + } + $verbs = $it.SelectNodes("./*[local-name()='Verb']") + foreach ($v in $verbs) { + $verbId = $v.GetAttribute('Id') + $clsidRaw = $v.GetAttribute('Clsid') + if ([string]::IsNullOrWhiteSpace($clsidRaw)) { continue } + $clsidUpper = $clsidRaw.Trim().ToUpperInvariant() + if (-not $clsidUpper.StartsWith('{')) { $clsidUpper = "{$clsidUpper}" } + + # 若 DLL 在 PackagedCom 中可找到,补充更精准的 DLL 路径与图标 + $dllPath = '' + foreach ($pcRoot in @('HKCU:\Software\Classes\PackagedCom\Package', 'HKLM:\Software\Classes\PackagedCom\Package')) { + $clsReg = Join-Path $pcRoot "$($pkg.PackageFullName)\Class\$clsidUpper" + if (Test-Path -LiteralPath $clsReg) { + $clsProps = Get-ItemProperty -LiteralPath $clsReg -ErrorAction SilentlyContinue + if ($null -ne $clsProps -and -not [string]::IsNullOrWhiteSpace($clsProps.DllPath)) { + $dllRel = [string]$clsProps.DllPath + $dllPath = if ([System.IO.Path]::IsPathRooted($dllRel)) { $dllRel } else { Join-Path $pkg.InstallLocation $dllRel } + if ([string]::IsNullOrWhiteSpace($iconDataUrl) -and (Test-Path -LiteralPath $dllPath)) { + $iconDataUrl = [ShlwapiHelper]::ExtractIconDataUrl($dllPath, '') + } + break + } + } + } + + # 构造更友好的中文/可读显示名 + $friendlyMap = @{ + 'QQExtension' = '通过 QQ 发送到 (Win11 现代扩展)' + 'HRContextMenu' = '火绒安全软件 (Win11 现代扩展)' + 'EditWithNotepadPlusPlus' = '以 Notepad++ 编辑 (Win11 现代扩展)' + 'kMoreCommand' = '360 压缩右键菜单 (Win11 现代扩展)' + 'FileLocksmithCommand' = 'Unlock with File Locksmith (Win11 现代扩展)' + 'PowerRenameCommand' = '使用 PowerRename 重命名 (Win11 现代扩展)' + 'ImageResizerCommand' = '调整图片大小 Image Resizer (Win11 现代扩展)' + } + $displayName = if ($friendlyMap.ContainsKey($verbId)) { + $friendlyMap[$verbId] + } elseif ($propDisp -ne $verbId) { + "$propDisp ($verbId)" + } else { + $propDisp + } + + foreach ($sid in $scopeIds) { + $list.Add([PSCustomObject]@{ + scopeId = $sid + pkgName = $pkg.Name + pkgFullName = $pkg.PackageFullName + verbId = $verbId + clsid = $clsidUpper + displayName = $displayName + dllPath = if ($dllPath) { $dllPath } else { $pkg.InstallLocation } + iconDataUrl = $iconDataUrl + }) + } + } + } + } catch {} + } + } catch {} + $script:Win11ExtCache = $list + return $script:Win11ExtCache +} + +function Invoke-Scan { + $blockedMap = Get-BlockedClsids + $results = New-Object System.Collections.Generic.List[object] + + foreach ($scope in $Scopes) { + foreach ($subPath in $scope.subPaths) { + foreach ($hive in $Hives) { + # 1. 扫描传统 shell 项(必须使用 -LiteralPath,防止 '*' 被 PowerShell 当作通配符展开) + $shellPsPath = Join-Path $hive.psRoot "$subPath\shell" + if (Test-Path -LiteralPath $shellPsPath) { + $subKeys = Get-ChildItem -LiteralPath $shellPsPath -ErrorAction SilentlyContinue + foreach ($sk in $subKeys) { + $props = Get-ItemProperty -LiteralPath $sk.PSPath -ErrorAction SilentlyContinue + $keyName = $sk.PSChildName + + $rawName = '' + if ($null -ne $props -and -not [string]::IsNullOrWhiteSpace($props.MUIVerb)) { + $rawName = [string]$props.MUIVerb + } elseif ($null -ne $props -and -not [string]::IsNullOrWhiteSpace($props.'(default)')) { + $rawName = [string]$props.'(default)' + } else { + $rawName = $keyName + } + + $displayName = Resolve-DisplayText $rawName + if ([string]::IsNullOrWhiteSpace($displayName)) { + $displayName = $keyName + } + + $commandText = '' + $cmdKey = Join-Path $sk.PSPath 'command' + if (Test-Path -LiteralPath $cmdKey) { + $cmdProps = Get-ItemProperty -LiteralPath $cmdKey -ErrorAction SilentlyContinue + if ($null -ne $cmdProps -and $null -ne $cmdProps.'(default)') { + $commandText = [string]$cmdProps.'(default)' + } + } + + $hasLegacyDisable = ($null -ne $props) -and ($props.PSObject.Properties.Name -contains 'LegacyDisable') + $hasProgOnly = ($null -ne $props) -and ($props.PSObject.Properties.Name -contains 'ProgrammaticAccessOnly') + $isExtended = ($null -ne $props) -and ($props.PSObject.Properties.Name -contains 'Extended') + $iconText = if ($null -ne $props -and $null -ne $props.Icon) { [string]$props.Icon } else { '' } + $positionText = if ($null -ne $props -and $null -ne $props.Position) { ([string]$props.Position).Trim() } else { '' } + $iconDataUrl = [ShlwapiHelper]::ExtractIconDataUrl($iconText, $commandText) + $regPath = "$($hive.regRoot)\$subPath\shell\$keyName" + + # 贴近 Windows Explorer 真实右键顺序的分组权重 + $sortGroup = if ($isExtended) { + 5 + } elseif ($positionText -ieq 'Top') { + 0 + } elseif ($positionText -ieq 'Bottom') { + 3 + } else { + 2 + } + + $results.Add([PSCustomObject]@{ + id = "$($scope.id)|$($hive.name)|$subPath|shell|$keyName" + scopeId = $scope.id + scopeLabel = $scope.label + kind = 'shell' + hive = $hive.name + keyName = $keyName + displayName = $displayName + rawName = $rawName + regPath = $regPath + clsid = '' + command = $commandText + icon = $iconText + iconDataUrl = $iconDataUrl + position = $positionText + sortGroup = $sortGroup + enabled = -not ($hasLegacyDisable -or $hasProgOnly) + disabledReason = if ($hasLegacyDisable) { 'LegacyDisable' } elseif ($hasProgOnly) { 'ProgrammaticAccessOnly' } else { '' } + isExtended = $isExtended + needsAdmin = $hive.needsAdmin + isSystemHint = ($keyName -in @('cmd', 'Powershell', 'WSL', 'open', 'print', 'edit', 'find')) + }) + } + } + + # 2. 扫描 shellex\ContextMenuHandlers COM 扩展(同样使用 -LiteralPath) + $shellexPsPath = Join-Path $hive.psRoot "$subPath\shellex\ContextMenuHandlers" + if (Test-Path -LiteralPath $shellexPsPath) { + $subKeys = Get-ChildItem -LiteralPath $shellexPsPath -ErrorAction SilentlyContinue + foreach ($sk in $subKeys) { + $props = Get-ItemProperty -LiteralPath $sk.PSPath -ErrorAction SilentlyContinue + $keyName = $sk.PSChildName + $clsid = '' + if ($null -ne $props -and -not [string]::IsNullOrWhiteSpace($props.'(default)')) { + $clsid = ([string]$props.'(default)').Trim() + } elseif ($keyName -match '^\{[0-9A-Fa-f-]+\}$') { + $clsid = $keyName.Trim() + } + + if ($clsid -notmatch '^\{[0-9A-Fa-f-]+\}$') { + continue + } + + $clsidUpper = $clsid.ToUpperInvariant() + $clsidInfo = Resolve-ClsidFriendlyInfo $clsidUpper + $displayName = if (-not [string]::IsNullOrWhiteSpace($clsidInfo.name)) { + if ($keyName -ne $clsidInfo.name -and ($keyName -notmatch '^\{')) { + "$($clsidInfo.name) ($keyName)" + } else { + $clsidInfo.name + } + } else { + $keyName + } + + $isBlocked = $blockedMap.ContainsKey($clsidUpper) + $blockedScope = if ($isBlocked) { $blockedMap[$clsidUpper] } else { '' } + $regPath = "$($hive.regRoot)\$subPath\shellex\ContextMenuHandlers\$keyName" + $isSysHint = ($keyName -in $SystemProtectedKeys) + $iconDataUrl = [ShlwapiHelper]::ExtractIconDataUrl($clsidInfo.dll, '') + + # 通过 HKCU Shell Extensions\Blocked 停用免管理员权限;仅当它被 HKLM 拦截时启用才需 UAC + $needsAdmin = ($blockedScope -eq 'HKLM') + $sortGroup = if ($isSysHint) { 4 } else { 1 } + + $results.Add([PSCustomObject]@{ + id = "$($scope.id)|$($hive.name)|$subPath|shellex|$keyName|$clsidUpper" + scopeId = $scope.id + scopeLabel = $scope.label + kind = 'shellex' + hive = $hive.name + keyName = $keyName + displayName = $displayName + rawName = $keyName + regPath = $regPath + clsid = $clsidUpper + command = $clsidInfo.dll + icon = '' + iconDataUrl = $iconDataUrl + position = '' + sortGroup = $sortGroup + enabled = -not $isBlocked + disabledReason = if ($isBlocked) { "Blocked($blockedScope)" } else { '' } + isExtended = $false + needsAdmin = $needsAdmin + isSystemHint = $isSysHint + }) + } + } + } + } + } + + # 3. 扫描 Win11 现代右键扩展(AppX / Sparse Package,如 QQ、火绒、新版 PowerToys、Notepad++、360 压缩) + $scopeLabelMap = @{ 'dir-bg' = '文件夹空白处'; 'file' = '文件'; 'dir' = '文件夹'; 'desktop-bg' = '桌面空白处' } + $win11Exts = Get-Win11ContextMenuExtensions + foreach ($ext in $win11Exts) { + $isBlocked = $blockedMap.ContainsKey($ext.clsid) + $blockedScope = if ($isBlocked) { $blockedMap[$ext.clsid] } else { '' } + $results.Add([PSCustomObject]@{ + id = "$($ext.scopeId)|APPX|win11|$($ext.verbId)|$($ext.clsid)" + scopeId = $ext.scopeId + scopeLabel = $scopeLabelMap[$ext.scopeId] + kind = 'shellex' + subKind = 'win11' + hive = 'APPX' + keyName = $ext.verbId + displayName = $ext.displayName + rawName = $ext.pkgName + regPath = "PackagedCom\\$($ext.pkgFullName)\\Class\\$($ext.clsid)" + clsid = $ext.clsid + command = $ext.dllPath + icon = '' + iconDataUrl = $ext.iconDataUrl + position = '' + sortGroup = 1 + enabled = -not $isBlocked + disabledReason = if ($isBlocked) { "Blocked($blockedScope)" } else { '' } + isExtended = $false + needsAdmin = ($blockedScope -eq 'HKLM') + isSystemHint = $false + }) + } + + # 按真实 Windows 右键菜单顺序排序(合并 HKCU/HKLM:场景 -> 分组权重 -> keyName 不区分大小写字母序) + $scopeRank = @{ 'dir-bg' = 0; 'file' = 1; 'dir' = 2; 'desktop-bg' = 3 } + $sortedResults = @($results | Sort-Object ` + @{ Expression = { $scopeRank[$_.scopeId] } }, ` + @{ Expression = { $_.sortGroup } }, ` + @{ Expression = { $_.keyName.ToLowerInvariant() } } + ) + + # 读取本插件历史修改记录数量 + $historyCount = Get-HistoryCount + + $output = [PSCustomObject]@{ + ok = $true + isAdmin = (Test-IsAdmin) + backupDir = $BackupDir + historyCount = $historyCount + items = $sortedResults + } + $output | ConvertTo-Json -Depth 6 -Compress +} + +function Save-BackupAndHistory { + param( + [array]$Operations + ) + if (-not (Test-Path $BackupDir)) { + New-Item -ItemType Directory -Force -Path $BackupDir | Out-Null + } + + $timestamp = Get-Date -Format 'yyyyMMdd-HHmmss' + $backupFiles = @() + + # 1. 导出修改前 .reg 备份文件(仅当目标注册表键存在时导出,并临时放宽 ErrorActionPreference 避免外部命令 stderr 中断) + $idx = 0 + $prevEap = $ErrorActionPreference + try { + $ErrorActionPreference = 'Continue' + foreach ($op in $Operations) { + $idx++ + $safeName = ($op.keyName -replace '[^A-Za-z0-9_-]', '_') + if ($op.kind -eq 'shell') { + $psCheckPath = 'Registry::' + $op.regPath + if (Test-Path -LiteralPath $psCheckPath) { + $regFile = Join-Path $BackupDir "${timestamp}_${idx}_${safeName}.reg" + $null = & reg.exe export $op.regPath $regFile /y 2>&1 + if (Test-Path -LiteralPath $regFile) { + $backupFiles += $regFile + } + } + } elseif ($op.kind -eq 'shellex') { + $blockedPsPath = 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Shell Extensions\Blocked' + $blockedRegPath = 'HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Shell Extensions\Blocked' + if (Test-Path -LiteralPath $blockedPsPath) { + $regFile = Join-Path $BackupDir "${timestamp}_${idx}_Blocked_${safeName}.reg" + $null = & reg.exe export $blockedRegPath $regFile /y 2>&1 + if (Test-Path -LiteralPath $regFile) { + $backupFiles += $regFile + } + } + } + } + } finally { + $ErrorActionPreference = $prevEap + } + + # 2. 更新可回滚历史记录 history.json(记录每个项最初的状态) + $historyPath = Join-Path $BackupDir 'history.json' + $historyList = New-Object System.Collections.Generic.List[object] + if (Test-Path $historyPath) { + try { + $existing = ConvertFrom-JsonArray (Get-Content $historyPath -Raw -Encoding UTF8) + foreach ($e in $existing) { + if ($null -ne $e) { $historyList.Add($e) } + } + } catch {} + } + + foreach ($op in $Operations) { + $found = $false + foreach ($h in $historyList) { + if ($h.id -eq $op.id) { + $found = $true + break + } + } + if (-not $found) { + $historyList.Add([PSCustomObject]@{ + id = $op.id + kind = $op.kind + hive = $op.hive + keyName = $op.keyName + displayName = $op.displayName + regPath = $op.regPath + clsid = $op.clsid + originalEnabled = [bool]$op.currentEnabled + needsAdmin = [bool]$op.needsAdmin + recordedAt = (Get-Date -Format 'yyyy-MM-dd HH:mm:ss') + }) + } + } + + $jsonText = ConvertTo-JsonArray -Items $historyList.ToArray() -Depth 5 + [System.IO.File]::WriteAllText($historyPath, $jsonText, [System.Text.UTF8Encoding]::new($false)) + return $backupFiles +} + +function Apply-SingleOperation { + param($Op) + + if ($Op.kind -eq 'shell') { + $psPath = 'Registry::' + $Op.regPath + if (-not (Test-Path -LiteralPath $psPath)) { + throw "注册表项不存在: $($Op.regPath)" + } + if ([bool]$Op.targetEnabled) { + # 启用:移除 LegacyDisable(以及如存在的 ProgrammaticAccessOnly) + $props = Get-ItemProperty -LiteralPath $psPath -ErrorAction SilentlyContinue + if ($null -ne $props -and ($props.PSObject.Properties.Name -contains 'LegacyDisable')) { + Remove-ItemProperty -LiteralPath $psPath -Name 'LegacyDisable' -Force + } + if ($null -ne $props -and ($props.PSObject.Properties.Name -contains 'ProgrammaticAccessOnly')) { + Remove-ItemProperty -LiteralPath $psPath -Name 'ProgrammaticAccessOnly' -Force + } + } else { + # 停用:写入微软原生 LegacyDisable 空字符串 + New-ItemProperty -LiteralPath $psPath -Name 'LegacyDisable' -Value '' -PropertyType String -Force | Out-Null + } + } elseif ($Op.kind -eq 'shellex') { + $clsid = ([string]$Op.clsid).Trim().ToUpperInvariant() + if ($clsid -notmatch '^\{[0-9A-Fa-f-]+\}$') { + throw "无效的 CLSID: $clsid" + } + $hkcuBlocked = 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Shell Extensions\Blocked' + $hklmBlocked = 'HKLM:\Software\Microsoft\Windows\CurrentVersion\Shell Extensions\Blocked' + + if ([bool]$Op.targetEnabled) { + if (Test-Path $hkcuBlocked) { + $p = Get-ItemProperty $hkcuBlocked -ErrorAction SilentlyContinue + if ($null -ne $p -and ($p.PSObject.Properties.Name -contains $clsid)) { + Remove-ItemProperty -Path $hkcuBlocked -Name $clsid -Force + } + } + if ((Test-IsAdmin) -and (Test-Path $hklmBlocked)) { + $p2 = Get-ItemProperty $hklmBlocked -ErrorAction SilentlyContinue + if ($null -ne $p2 -and ($p2.PSObject.Properties.Name -contains $clsid)) { + Remove-ItemProperty -Path $hklmBlocked -Name $clsid -Force + } + } + } else { + if (-not (Test-Path $hkcuBlocked)) { + New-Item -Path $hkcuBlocked -Force | Out-Null + } + $desc = "ALLTool Disabled: $($Op.displayName)" + New-ItemProperty -Path $hkcuBlocked -Name $clsid -Value $desc -PropertyType String -Force | Out-Null + } + } +} + +function Invoke-OperationsWithElevation { + param([array]$Operations) + + $needsAdminOps = @($Operations | Where-Object { [bool]$_.needsAdmin }) + $normalOps = @($Operations | Where-Object { -not [bool]$_.needsAdmin }) + + # 先执行免管理员权限的项 + foreach ($op in $normalOps) { + Apply-SingleOperation -Op $op + } + + # 再处理需要管理员权限的项 + if ($needsAdminOps.Count -gt 0) { + if (Test-IsAdmin) { + foreach ($op in $needsAdminOps) { + Apply-SingleOperation -Op $op + } + } else { + # 写入临时提权任务文件并只弹一次 UAC + $tempId = [Guid]::NewGuid().ToString('N') + $elevPayload = Join-Path $env:TEMP "alltool_ctx_${tempId}.json" + $elevResult = Join-Path $env:TEMP "alltool_ctx_${tempId}_res.json" + $elevScript = Join-Path $env:TEMP "alltool_ctx_${tempId}.ps1" + + $payloadJson = ConvertTo-JsonArray -Items $needsAdminOps -Depth 5 + [System.IO.File]::WriteAllText($elevPayload, $payloadJson, [System.Text.UTF8Encoding]::new($false)) + + $scriptBody = @" +`$ErrorActionPreference = 'Stop' +`$resPath = '$($elevResult.Replace("'", "''"))' +try { + `$ops = Get-Content '$($elevPayload.Replace("'", "''"))' -Raw -Encoding UTF8 | ConvertFrom-Json + foreach (`$op in @(`$ops)) { + if (`$op.kind -eq 'shell') { + `$psPath = 'Registry::' + `$op.regPath + if (-not (Test-Path -LiteralPath `$psPath)) { throw "注册表项不存在: `$(`$op.regPath)" } + if ([bool]`$op.targetEnabled) { + `$props = Get-ItemProperty -LiteralPath `$psPath -ErrorAction SilentlyContinue + if (`$null -ne `$props -and (`$props.PSObject.Properties.Name -contains 'LegacyDisable')) { + Remove-ItemProperty -LiteralPath `$psPath -Name 'LegacyDisable' -Force + } + if (`$null -ne `$props -and (`$props.PSObject.Properties.Name -contains 'ProgrammaticAccessOnly')) { + Remove-ItemProperty -LiteralPath `$psPath -Name 'ProgrammaticAccessOnly' -Force + } + } else { + New-ItemProperty -LiteralPath `$psPath -Name 'LegacyDisable' -Value '' -PropertyType String -Force | Out-Null + } + } elseif (`$op.kind -eq 'shellex') { + `$clsid = ([string]`$op.clsid).Trim().ToUpperInvariant() + `$hklmBlocked = 'HKLM:\Software\Microsoft\Windows\CurrentVersion\Shell Extensions\Blocked' + if ([bool]`$op.targetEnabled -and (Test-Path `$hklmBlocked)) { + `$p = Get-ItemProperty `$hklmBlocked -ErrorAction SilentlyContinue + if (`$null -ne `$p -and (`$p.PSObject.Properties.Name -contains `$clsid)) { + Remove-ItemProperty -Path `$hklmBlocked -Name `$clsid -Force + } + } + } + } + [System.IO.File]::WriteAllText(`$resPath, '{"ok":true}', [System.Text.UTF8Encoding]::new(`$false)) +} catch { + `$errObj = @{ ok = `$false; error = `$_.Exception.Message } | ConvertTo-Json -Compress + [System.IO.File]::WriteAllText(`$resPath, `$errObj, [System.Text.UTF8Encoding]::new(`$false)) + exit 1 +} +"@ + [System.IO.File]::WriteAllText($elevScript, $scriptBody, [System.Text.UTF8Encoding]::new($false)) + + try { + $proc = Start-Process -FilePath 'powershell.exe' ` + -ArgumentList @('-NoProfile', '-ExecutionPolicy', 'Bypass', '-WindowStyle', 'Hidden', '-File', $elevScript) ` + -Verb RunAs -Wait -PassThru + + if (-not (Test-Path $elevResult)) { + throw "管理员提权未完成(可能已取消 UAC 授权,退出码: $($proc.ExitCode))" + } + $resObj = Get-Content $elevResult -Raw -Encoding UTF8 | ConvertFrom-Json + if (-not $resObj.ok) { + throw "提权执行失败: $($resObj.error)" + } + } finally { + Remove-Item $elevPayload, $elevResult, $elevScript -Force -ErrorAction SilentlyContinue + } + } + } +} + +function Get-HistoryCount { + $historyPath = Join-Path $BackupDir 'history.json' + $historyCount = 0 + if (Test-Path $historyPath) { + try { + $hist = ConvertFrom-JsonArray (Get-Content $historyPath -Raw -Encoding UTF8) + $historyCount = $hist.Count + } catch {} + } + return $historyCount +} + +function Invoke-RestoreAll { + $historyPath = Join-Path $BackupDir 'history.json' + if (-not (Test-Path $historyPath)) { + return ([PSCustomObject]@{ ok = $true; restoredCount = 0; historyCount = 0; message = '暂无需要还原的修改记录' } | ConvertTo-Json -Compress) + } + $hist = ConvertFrom-JsonArray (Get-Content $historyPath -Raw -Encoding UTF8) + if ($hist.Count -eq 0) { + return ([PSCustomObject]@{ ok = $true; restoredCount = 0; historyCount = 0; message = '暂无需要还原的修改记录' } | ConvertTo-Json -Compress) + } + $restoreOps = @() + foreach ($h in $hist) { + $restoreOps += [PSCustomObject]@{ + id = $h.id + kind = $h.kind + hive = $h.hive + keyName = $h.keyName + displayName = $h.displayName + regPath = $h.regPath + clsid = $h.clsid + targetEnabled = [bool]$h.originalEnabled + needsAdmin = [bool]$h.needsAdmin + } + } + Invoke-OperationsWithElevation -Operations $restoreOps + Remove-Item $historyPath -Force -ErrorAction SilentlyContinue + return ([PSCustomObject]@{ + ok = $true + restoredCount = $restoreOps.Count + historyCount = 0 + needsExplorerRestart = (@($restoreOps | Where-Object { $_.kind -eq 'shellex' }).Count -gt 0) + } | ConvertTo-Json -Compress) +} + +function Invoke-RestartExplorer { + Stop-Process -Name explorer -Force -ErrorAction SilentlyContinue + Start-Sleep -Milliseconds 600 + if (-not (Get-Process -Name explorer -ErrorAction SilentlyContinue)) { + Start-Process explorer.exe + } + return ([PSCustomObject]@{ ok = $true } | ConvertTo-Json -Compress) +} + +if ($Action -ne 'lib') { + try { + switch ($Action) { + 'scan' { + Invoke-Scan + } + 'toggle' { + if ([string]::IsNullOrWhiteSpace($PayloadFile) -or -not (Test-Path $PayloadFile)) { + throw '缺少有效的 PayloadFile 参数' + } + $raw = Get-Content $PayloadFile -Raw -Encoding UTF8 | ConvertFrom-Json + $ops = if ($raw -is [System.Array]) { $raw } else { @($raw) } + if ($ops.Count -eq 0) { + throw '操作列表为空' + } + $backups = Save-BackupAndHistory -Operations $ops + Invoke-OperationsWithElevation -Operations $ops + $needsExplorerRestart = (@($ops | Where-Object { $_.kind -eq 'shellex' }).Count -gt 0) + [PSCustomObject]@{ + ok = $true + appliedCount = $ops.Count + backupCount = $backups.Count + backupDir = $BackupDir + historyCount = (Get-HistoryCount) + needsExplorerRestart = $needsExplorerRestart + } | ConvertTo-Json -Compress + } + 'restore-all' { + Invoke-RestoreAll + } + 'restart-explorer' { + Invoke-RestartExplorer + } + } + } catch { + [PSCustomObject]@{ + ok = $false + error = $_.Exception.Message + } | ConvertTo-Json -Compress + exit 1 + } +} diff --git a/plugins/win-context-menu/scripts/elevated-worker.ps1 b/plugins/win-context-menu/scripts/elevated-worker.ps1 new file mode 100644 index 000000000..9a122d2f5 --- /dev/null +++ b/plugins/win-context-menu/scripts/elevated-worker.ps1 @@ -0,0 +1,145 @@ +#requires -Version 5.1 +<# +.SYNOPSIS + Windows 右键菜单管理 - 常驻提权本地工作进程(一次 UAC,全程免重复弹窗,毫秒级响应) +.DESCRIPTION + - 仅监听 127.0.0.1:,所有请求强制校验随机 Token + - 启动时预热一次 context-menu-manager.ps1(含 SHLoadIndirectString),后续 scan/toggle/restore 毫秒级响应 + - 空闲超过 IdleTimeoutSeconds(默认 900 秒 = 15 分钟)或收到 /shutdown 自动优雅退出 +#> +param( + [Parameter(Mandatory = $true)] + [int]$Port, + + [Parameter(Mandatory = $true)] + [string]$Token, + + [Parameter(Mandatory = $true)] + [string]$BackupDir, + + [Parameter(Mandatory = $true)] + [string]$ManagerScriptPath, + + [string]$ReadyFile = '', + [int]$IdleTimeoutSeconds = 900 +) + +$ErrorActionPreference = 'Stop' +[Console]::OutputEncoding = [System.Text.Encoding]::UTF8 +$OutputEncoding = [System.Text.Encoding]::UTF8 + +# 加载核心引擎函数(通过 dot-source 方式,避免重复冷启动与重复 Add-Type 编译) +. $ManagerScriptPath -Action 'lib' -BackupDir $BackupDir + +$listener = New-Object System.Net.HttpListener +$prefix = "http://127.0.0.1:${Port}/" +$listener.Prefixes.Add($prefix) +$listener.Start() + +if (-not [string]::IsNullOrWhiteSpace($ReadyFile)) { + $readyJson = @{ ok = $true; port = $Port; pid = $PID; isAdmin = (Test-IsAdmin) } | ConvertTo-Json -Compress + [System.IO.File]::WriteAllText($ReadyFile, $readyJson, [System.Text.UTF8Encoding]::new($false)) +} + +function Send-JsonResponse { + param( + [System.Net.HttpListenerResponse]$Response, + [int]$StatusCode, + [string]$JsonText + ) + $Response.StatusCode = $StatusCode + $Response.ContentType = 'application/json; charset=utf-8' + $bytes = [System.Text.Encoding]::UTF8.GetBytes($JsonText) + $Response.ContentLength64 = $bytes.Length + $Response.OutputStream.Write($bytes, 0, $bytes.Length) + $Response.OutputStream.Close() +} + +$lastActive = Get-Date + +try { + while ($listener.IsListening) { + $asyncResult = $listener.BeginGetContext($null, $null) + while (-not $asyncResult.AsyncWaitHandle.WaitOne(500)) { + if (((Get-Date) - $lastActive).TotalSeconds -ge $IdleTimeoutSeconds) { + $listener.Stop() + break + } + } + if (-not $listener.IsListening) { break } + + $context = $null + try { + $context = $listener.EndGetContext($asyncResult) + } catch { + break + } + + $lastActive = Get-Date + $req = $context.Request + $res = $context.Response + + # 强制校验随机 Token + $reqToken = $req.Headers['X-ALLTool-Token'] + if ($reqToken -ne $Token) { + Send-JsonResponse -Response $res -StatusCode 403 -JsonText '{"ok":false,"error":"Forbidden"}' + continue + } + + $route = $req.Url.AbsolutePath.ToLowerInvariant() + try { + switch ($route) { + '/health' { + $body = @{ ok = $true; pid = $PID; isAdmin = (Test-IsAdmin); schemaVersion = 5 } | ConvertTo-Json -Compress + Send-JsonResponse -Response $res -StatusCode 200 -JsonText $body + } + '/scan' { + $body = Invoke-Scan + Send-JsonResponse -Response $res -StatusCode 200 -JsonText $body + } + '/toggle' { + $reader = New-Object System.IO.StreamReader($req.InputStream, [System.Text.Encoding]::UTF8) + $rawBody = $reader.ReadToEnd() + $reader.Close() + $parsed = ConvertFrom-Json $rawBody + $ops = if ($parsed -is [System.Array]) { $parsed } else { @($parsed) } + if ($ops.Count -eq 0) { throw '操作列表为空' } + $backups = Save-BackupAndHistory -Operations $ops + Invoke-OperationsWithElevation -Operations $ops + $needsExplorerRestart = (@($ops | Where-Object { $_.kind -eq 'shellex' }).Count -gt 0) + $historyCount = Get-HistoryCount + $body = [PSCustomObject]@{ + ok = $true + appliedCount = $ops.Count + backupCount = $backups.Count + backupDir = $BackupDir + historyCount = $historyCount + needsExplorerRestart = $needsExplorerRestart + } | ConvertTo-Json -Compress + Send-JsonResponse -Response $res -StatusCode 200 -JsonText $body + } + '/restore-all' { + $body = Invoke-RestoreAll + Send-JsonResponse -Response $res -StatusCode 200 -JsonText $body + } + '/restart-explorer' { + $body = Invoke-RestartExplorer + Send-JsonResponse -Response $res -StatusCode 200 -JsonText $body + } + '/shutdown' { + Send-JsonResponse -Response $res -StatusCode 200 -JsonText '{"ok":true}' + $listener.Stop() + } + default { + Send-JsonResponse -Response $res -StatusCode 404 -JsonText '{"ok":false,"error":"Not Found"}' + } + } + } catch { + $errJson = @{ ok = $false; error = $_.Exception.Message } | ConvertTo-Json -Compress + Send-JsonResponse -Response $res -StatusCode 200 -JsonText $errJson + } + } +} finally { + if ($listener.IsListening) { $listener.Stop() } + $listener.Close() +} diff --git a/plugins/win-context-menu/style.css b/plugins/win-context-menu/style.css new file mode 100644 index 000000000..7f8a1eecc --- /dev/null +++ b/plugins/win-context-menu/style.css @@ -0,0 +1,415 @@ +:root { + --bg: #f6f7f9; + --surface: #ffffff; + --surface-hover: #f0f3f8; + --border: #e5e7eb; + --text: #1f2937; + --text-muted: #6b7280; + --primary: #2563eb; + --primary-hover: #1d4ed8; + --danger: #dc2626; + --danger-bg: #fef2f2; + --warn-text: #b45309; + --warn-bg: #fffbeb; + --ok-text: #047857; + --ok-bg: #ecfdf5; + --badge-bg: #f3f4f6; + --shadow: 0 1px 2px rgba(0, 0, 0, 0.04); +} + +[data-theme="dark"] { + --bg: #181a1f; + --surface: #22252c; + --surface-hover: #2a2e37; + --border: #323743; + --text: #e5e7eb; + --text-muted: #9ca3af; + --primary: #3b82f6; + --primary-hover: #2563eb; + --danger: #ef4444; + --danger-bg: #3b1d20; + --warn-text: #fbbf24; + --warn-bg: #382c15; + --ok-text: #34d399; + --ok-bg: #14332a; + --badge-bg: #2f3440; + --shadow: 0 1px 3px rgba(0, 0, 0, 0.25); +} + +* { + box-sizing: border-box; + margin: 0; + padding: 0; +} + +html, body { + height: 100%; + font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "Microsoft YaHei UI", sans-serif; + font-size: 13px; + color: var(--text); + background: var(--bg); + user-select: none; +} + +.app { + display: flex; + flex-direction: column; + height: 100vh; +} + +.topbar { + background: var(--surface); + border-bottom: 1px solid var(--border); + padding: 10px 14px; + display: flex; + flex-direction: column; + gap: 8px; +} + +.tabs { + display: flex; + gap: 6px; + flex-wrap: wrap; +} + +.tab { + border: 1px solid var(--border); + background: transparent; + color: var(--text-muted); + padding: 5px 11px; + border-radius: 6px; + cursor: pointer; + font-size: 12px; + transition: all 0.15s; +} + +.tab:hover { + background: var(--surface-hover); + color: var(--text); +} + +.tab.active { + background: var(--primary); + border-color: var(--primary); + color: #ffffff; + font-weight: 500; +} + +.toolbar { + display: flex; + gap: 8px; + align-items: center; +} + +.toolbar input { + flex: 1; + height: 30px; + padding: 0 10px; + border-radius: 6px; + border: 1px solid var(--border); + background: var(--bg); + color: var(--text); + outline: none; +} + +.toolbar input:focus { + border-color: var(--primary); +} + +.toolbar select { + height: 30px; + padding: 0 8px; + border-radius: 6px; + border: 1px solid var(--border); + background: var(--bg); + color: var(--text); + outline: none; +} + +.btn { + border: 1px solid transparent; + border-radius: 6px; + padding: 6px 12px; + cursor: pointer; + font-size: 12px; + font-weight: 500; + transition: opacity 0.15s, background 0.15s; +} + +.btn:disabled { + opacity: 0.45; + cursor: not-allowed; +} + +.btn-sm { + padding: 4px 10px; +} + +.btn-primary { + background: var(--primary); + color: #fff; +} + +.btn-primary:hover:not(:disabled) { + background: var(--primary-hover); +} + +.btn-secondary { + background: var(--surface); + border-color: var(--border); + color: var(--text); +} + +.btn-secondary:hover:not(:disabled) { + background: var(--surface-hover); +} + +.btn-danger { + background: var(--danger-bg); + border-color: var(--danger); + color: var(--danger); +} + +.btn-danger:hover:not(:disabled) { + background: var(--danger); + color: #fff; +} + +.btn-ok { + background: var(--ok-bg); + border-color: var(--ok-text); + color: var(--ok-text); +} + +.btn-ok:hover:not(:disabled) { + opacity: 0.9; +} + +.banner { + background: var(--warn-bg); + color: var(--warn-text); + border-bottom: 1px solid var(--border); + padding: 8px 14px; + display: flex; + align-items: center; + justify-content: space-between; + font-size: 12px; +} + +.hidden { + display: none !important; +} + +.content { + flex: 1; + overflow-y: auto; + padding: 10px 14px; +} + +.empty-state { + text-align: center; + color: var(--text-muted); + padding: 48px 16px; +} + +.item-list { + display: flex; + flex-direction: column; + gap: 8px; +} + +.card { + background: var(--surface); + border: 1px solid var(--border); + border-radius: 8px; + padding: 10px 12px; + display: flex; + align-items: center; + justify-content: space-between; + gap: 12px; + box-shadow: var(--shadow); + transition: border-color 0.15s, opacity 0.15s; +} + +.card.disabled { + opacity: 0.68; +} + +.card-icon { + width: 28px; + height: 28px; + border-radius: 6px; + background: var(--bg); + border: 1px solid var(--border); + display: flex; + align-items: center; + justify-content: center; + flex-shrink: 0; + overflow: hidden; +} + +.card-icon img { + width: 20px; + height: 20px; + object-fit: contain; + display: block; +} + +.card-icon-fallback { + font-size: 13px; + color: var(--text-muted); + line-height: 1; +} + +.card-main { + min-width: 0; + flex: 1; + display: flex; + flex-direction: column; + gap: 4px; +} + +.card-title-row { + display: flex; + align-items: center; + gap: 6px; + flex-wrap: wrap; +} + +.card-title { + font-size: 13.5px; + font-weight: 600; + color: var(--text); +} + +.badge { + font-size: 11px; + padding: 1px 6px; + border-radius: 4px; + background: var(--badge-bg); + color: var(--text-muted); +} + +.badge-ok { + background: var(--ok-bg); + color: var(--ok-text); +} + +.badge-warn { + background: var(--warn-bg); + color: var(--warn-text); +} + +.badge-danger { + background: var(--danger-bg); + color: var(--danger); +} + +.card-meta { + font-size: 11.5px; + color: var(--text-muted); + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; + user-select: text; +} + +/* 开关样式 */ +.switch { + position: relative; + display: inline-block; + width: 40px; + height: 22px; + flex-shrink: 0; +} + +.switch input { + opacity: 0; + width: 0; + height: 0; +} + +.slider { + position: absolute; + cursor: pointer; + inset: 0; + background-color: #9ca3af; + border-radius: 22px; + transition: 0.2s; +} + +.slider::before { + position: absolute; + content: ""; + height: 16px; + width: 16px; + left: 3px; + bottom: 3px; + background-color: #ffffff; + border-radius: 50%; + transition: 0.2s; +} + +.switch input:checked + .slider { + background-color: var(--primary); +} + +.switch input:checked + .slider::before { + transform: translateX(18px); +} + +.switch input:disabled + .slider { + opacity: 0.5; + cursor: wait; +} + +.footer { + background: var(--surface); + border-top: 1px solid var(--border); + padding: 8px 14px; + display: flex; + align-items: center; + justify-content: space-between; + gap: 8px; +} + +.footer-info { + display: flex; + align-items: center; + gap: 6px; + font-size: 12px; + color: var(--text-muted); +} + +.footer-actions { + display: flex; + gap: 8px; +} + +.link-btn { + background: none; + border: none; + color: var(--primary); + cursor: pointer; + font-size: 12px; + padding: 0; +} + +.link-btn:hover { + text-decoration: underline; +} + +.toast { + position: fixed; + left: 50%; + bottom: 52px; + transform: translateX(-50%); + background: rgba(17, 24, 39, 0.92); + color: #fff; + padding: 8px 14px; + border-radius: 8px; + font-size: 12px; + max-width: 85%; + text-align: center; + z-index: 999; +} diff --git a/plugins/win-context-menu/tests/run-tests.mjs b/plugins/win-context-menu/tests/run-tests.mjs new file mode 100644 index 000000000..6a19aa1a9 --- /dev/null +++ b/plugins/win-context-menu/tests/run-tests.mjs @@ -0,0 +1,227 @@ +// Windows 右键菜单管理插件自动化测试脚本(Node.js) +// 覆盖:L1 静态契约 -> L2 Preload 桥接 -> L3 常驻 Worker 毫秒级 scan/toggle/restore/shutdown 完整沙箱闭环 +import assert from "node:assert/strict"; +import crypto from "node:crypto"; +import fs from "node:fs"; +import http from "node:http"; +import net from "node:net"; +import os from "node:os"; +import path from "node:path"; +import { execFileSync, spawn } from "node:child_process"; +import { createRequire } from "node:module"; +import { fileURLToPath } from "node:url"; + +const __dirname = path.dirname(fileURLToPath(import.meta.url)); +const PLUGIN_DIR = path.resolve(__dirname, ".."); +const require = createRequire(import.meta.url); + +function runReg(args) { + return execFileSync("reg.exe", args, { encoding: "utf8", windowsHide: true }); +} + +function getFreePort() { + return new Promise((resolve, reject) => { + const srv = net.createServer(); + srv.on("error", reject); + srv.listen(0, "127.0.0.1", () => { + const port = srv.address().port; + srv.close(() => resolve(port)); + }); + }); +} + +function httpJson(port, token, route, method = "GET", bodyObj = null) { + return new Promise((resolve, reject) => { + const bodyText = bodyObj !== null ? JSON.stringify(bodyObj) : ""; + const headers = { "X-ALLTool-Token": token }; + if (bodyText) { + headers["Content-Type"] = "application/json; charset=utf-8"; + headers["Content-Length"] = Buffer.byteLength(bodyText, "utf8"); + } + const req = http.request({ hostname: "127.0.0.1", port, path: route, method, headers }, (res) => { + const chunks = []; + res.on("data", (c) => chunks.push(c)); + res.on("end", () => { + try { + resolve({ status: res.statusCode, data: JSON.parse(Buffer.concat(chunks).toString("utf8")) }); + } catch (err) { + reject(err); + } + }); + }); + req.on("error", reject); + if (bodyText) req.write(bodyText); + req.end(); + }); +} + +async function main() { + console.log("=== [1/4] 静态配置与文件完整性校验 ==="); + const manifest = JSON.parse(fs.readFileSync(path.join(PLUGIN_DIR, "plugin.json"), "utf8")); + assert.equal(manifest.name, "win-context-menu"); + assert.ok(Array.isArray(manifest.platform) && manifest.platform.includes("win32")); + for (const rel of [manifest.main, manifest.preload, manifest.logo, "scripts/context-menu-manager.ps1", "scripts/elevated-worker.ps1"]) { + assert.ok(fs.existsSync(path.join(PLUGIN_DIR, rel)), `缺少文件: ${rel}`); + } + console.log(" PASS: plugin.json 与所有脚本/入口文件完整"); + + console.log("=== [2/4] Preload 挂载与 API 契约校验 ==="); + globalThis.window = { ztools: {} }; + require(path.join(PLUGIN_DIR, "preload.js")); + for (const fn of ["getSessionStatus", "startElevatedSession", "stopElevatedSession", "scan", "toggleItems", "restoreAll", "restartExplorer"]) { + assert.equal(typeof globalThis.window.ctxMenuApi[fn], "function", `缺少 API: ${fn}`); + } + console.log(" PASS: preload.js 全部桥接方法就绪"); + + console.log("=== [2.5/4] Start-Process -WindowStyle Hidden + UTF-8 BOM 启动器中文路径静默校验 ==="); + const hiddenOut = path.join(os.tmpdir(), `alltool_hidden_out_${Date.now()}.txt`); + const hiddenLauncher = path.join(os.tmpdir(), `alltool_hidden_launcher_${Date.now()}.ps1`); + try { + const manifestCnPath = path.join(PLUGIN_DIR, "plugin.json"); + const launcherScript = `if (Test-Path -LiteralPath '${manifestCnPath}') { Set-Content -LiteralPath '${hiddenOut}' -Value 'OK' }`; + fs.writeFileSync(hiddenLauncher, "\uFEFF" + launcherScript, "utf8"); + const cmd = `Start-Process -FilePath 'powershell.exe' -WindowStyle Hidden -Wait -ArgumentList @('-NoProfile','-ExecutionPolicy','Bypass','-WindowStyle','Hidden','-File','${hiddenLauncher}')`; + execFileSync("powershell.exe", ["-NoProfile", "-ExecutionPolicy", "Bypass", "-WindowStyle", "Hidden", "-Command", cmd], { windowsHide: true }); + assert.ok(fs.existsSync(hiddenOut) && fs.readFileSync(hiddenOut, "utf8").trim() === "OK", "Hidden 中文路径启动失败"); + console.log(" PASS: Start-Process -WindowStyle Hidden 中文路径零蓝框拉起验证通过"); + } finally { + try { if (fs.existsSync(hiddenOut)) fs.unlinkSync(hiddenOut); } catch (_) {} + try { if (fs.existsSync(hiddenLauncher)) fs.unlinkSync(hiddenLauncher); } catch (_) {} + } + + console.log("=== [3/4] 常驻 Worker 毫秒级 scan / 沙箱 toggle / restore-all / shutdown 闭环测试 ==="); + const port = await getFreePort(); + const token = crypto.randomBytes(16).toString("hex"); + const sandboxBackupDir = path.join(os.tmpdir(), `alltool_worker_test_${Date.now()}`); + const readyFile = path.join(os.tmpdir(), `alltool_worker_ready_${Date.now()}.json`); + const sandboxKey = "HKEY_CURRENT_USER\\Software\\ALLTool_SandboxTest_CtxMenu"; + + const workerProc = spawn( + "powershell.exe", + [ + "-NoProfile", + "-ExecutionPolicy", + "Bypass", + "-File", + path.join(PLUGIN_DIR, "scripts", "elevated-worker.ps1"), + "-Port", + String(port), + "-Token", + token, + "-BackupDir", + sandboxBackupDir, + "-ManagerScriptPath", + path.join(PLUGIN_DIR, "scripts", "context-menu-manager.ps1"), + "-ReadyFile", + readyFile, + ], + { windowsHide: true, stdio: "ignore" } + ); + + // 等待 Worker 预热就绪 + const tStart = Date.now(); + while (!fs.existsSync(readyFile) && Date.now() - tStart < 15000) { + await new Promise((r) => setTimeout(r, 120)); + } + assert.ok(fs.existsSync(readyFile), "常驻 Worker 启动超时"); + console.log(` PASS: 常驻 Worker 预热就绪 (${Date.now() - tStart}ms)`); + + runReg(["add", sandboxKey, "/ve", "/t", "REG_SZ", "/d", "ALLTool Worker 测试项", "/f"]); + + try { + // 3.1 Token 鉴权拦截校验 + const badRes = await httpJson(port, "wrong-token", "/health", "GET"); + assert.equal(badRes.status, 403, "错误 Token 未被拦截"); + + // 3.2 热态 scan 耗时、图标提取与排序测试 + const tScan = Date.now(); + const scanRes = await httpJson(port, token, "/scan", "GET"); + const scanMs = Date.now() - tScan; + assert.equal(scanRes.data.ok, true); + assert.ok(scanRes.data.items.length > 0); + const dirBgItems = scanRes.data.items.filter((i) => i.scopeId === "dir-bg"); + const fileItems = scanRes.data.items.filter((i) => i.scopeId === "file"); + const withIcons = dirBgItems.filter((i) => i.iconDataUrl && i.iconDataUrl.startsWith("data:image/png;base64,")); + assert.ok(withIcons.length > 0, "未提取到任何右键菜单图标"); + const hasQQ = fileItems.some((i) => i.keyName === "QQExtension"); + const hasHR = fileItems.some((i) => i.keyName === "HRContextMenu"); + const hasFileLocksmith = fileItems.some((i) => i.keyName === "FileLocksmithExt" || i.keyName === "FileLocksmithCommand"); + assert.ok(hasQQ, "文件右键未检出 QQExtension"); + assert.ok(hasHR, "文件右键未检出 HRContextMenu(火绒)"); + assert.ok(hasFileLocksmith, "文件右键未检出 FileLocksmith"); + console.log(` PASS: 常驻 Worker 热态 scan 成功,共 ${scanRes.data.items.length} 项,耗时 ${scanMs}ms`); + console.log(` PASS: 文件夹空白处 ${dirBgItems.length} 项(真实图标 ${withIcons.length} 项);文件右键 ${fileItems.length} 项(已检出 QQ / 火绒 / FileLocksmith / PowerRename 等 Win11 现代扩展与 AllFilesystemObjects)`); + + // 3.3 沙箱 toggle 停用测试(同时覆盖 shell 项与 shellex/Win11 现代扩展!) + const testClsid = "{11111111-2222-3333-4444-555555555555}"; + const tToggle = Date.now(); + const disRes = await httpJson(port, token, "/toggle", "POST", [ + { + id: "sandbox|HKCU|shell|ALLTool_SandboxTest_CtxMenu", + kind: "shell", + hive: "HKCU", + keyName: "ALLTool_SandboxTest_CtxMenu", + displayName: "ALLTool Worker 测试项", + regPath: sandboxKey, + clsid: "", + currentEnabled: true, + targetEnabled: false, + needsAdmin: false, + }, + { + id: `sandbox|APPX|win11|SandboxWin11Ext|${testClsid}`, + kind: "shellex", + hive: "APPX", + keyName: "SandboxWin11Ext", + displayName: "ALLTool Win11 沙箱扩展", + regPath: `PackagedCom\\SandboxPkg\\Class\\${testClsid}`, + clsid: testClsid, + currentEnabled: true, + targetEnabled: false, + needsAdmin: false, + }, + ]); + const toggleMs = Date.now() - tToggle; + assert.equal(disRes.data.ok, true, `停用失败: ${disRes.data.error}`); + assert.equal(disRes.data.historyCount, 2); + const q1 = runReg(["query", sandboxKey, "/v", "LegacyDisable"]); + assert.ok(q1.includes("LegacyDisable")); + const q2 = runReg(["query", "HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\Shell Extensions\\Blocked", "/v", testClsid]); + assert.ok(q2.includes(testClsid), "Blocked 拦截表未写入测试 CLSID"); + console.log(` PASS: 常驻 Worker 沙箱停用(shell + shellex/Win11 现代扩展)+ 自动备份成功,耗时 ${toggleMs}ms`); + + // 3.4 一键还原测试 + const tRestore = Date.now(); + const restoreRes = await httpJson(port, token, "/restore-all", "POST", {}); + const restoreMs = Date.now() - tRestore; + assert.equal(restoreRes.data.ok, true); + assert.equal(restoreRes.data.restoredCount, 2); + assert.equal(restoreRes.data.historyCount, 0); + let clsidStillBlocked = false; + try { + runReg(["query", "HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\Shell Extensions\\Blocked", "/v", testClsid]); + clsidStillBlocked = true; + } catch (_) { + clsidStillBlocked = false; + } + assert.equal(clsidStillBlocked, false, "还原后测试 CLSID 仍残留在 Blocked 表中"); + console.log(` PASS: 常驻 Worker 一键还原(shell + shellex/Win11)成功,耗时 ${restoreMs}ms`); + + // 3.5 优雅关闭 Worker + const shutRes = await httpJson(port, token, "/shutdown", "POST", {}); + assert.equal(shutRes.data.ok, true); + console.log(" PASS: 常驻 Worker 已优雅关闭"); + } finally { + try { workerProc.kill(); } catch (_) {} + try { runReg(["delete", sandboxKey, "/f"]); } catch (_) {} + try { if (fs.existsSync(readyFile)) fs.unlinkSync(readyFile); } catch (_) {} + try { if (fs.existsSync(sandboxBackupDir)) fs.rmSync(sandboxBackupDir, { recursive: true, force: true }); } catch (_) {} + } + + console.log("=== [4/4] 全部测试通过 ==="); +} + +main().catch((err) => { + console.error("TEST FAILED:", err); + process.exit(1); +});