diff --git a/extensions/data-recovery/README.md b/extensions/data-recovery/README.md deleted file mode 100644 index 37a2875..0000000 --- a/extensions/data-recovery/README.md +++ /dev/null @@ -1,22 +0,0 @@ -# 数据恢复 - -开发中,暂不在插件市场提供:客户端目前只能列出 C、D、E 盘回收站里的文件,且只给出回收站内部的 $R 文件名,没有原始文件名、原路径和删除时间,用户难以辨认要找回的文件;也不能扫描已清空回收站、格式化或被覆盖的数据。等客户端能读出回收站文件的原始名称与路径、提供磁盘级的已删除文件扫描能力,并在 Windows 上实测通过后再发布。 - -列出 Windows 回收站里的文件,把勾选的文件复制到桌面的 ZToolsRecovered 文件夹。 - -## 使用 - -- 命令:在启动框搜索“数据恢复”打开。 -- 扫描 C、D、E 盘回收站里的文件(每个用户的回收站只读取前 120 个条目,总共最多列出 200 个文件;回收站里被删除的文件夹不会列出),按扩展名分为文档、图片、视频音频、压缩包与代码、其他,可勾选;打开时不勾选任何文件。 -- 列表显示的是回收站内部的文件名(以 `$R` 开头,保留扩展名)和文件的修改时间,不显示原始文件名、原路径和删除时间,恢复出来的文件也使用这个名字。 -- Enter:把勾选的文件复制到桌面 ZToolsRecovered 文件夹里本次新建的、以时间命名的子文件夹(没有勾选时只提示,不做处理);Ctrl+Enter:在资源管理器中定位该文件;Ctrl+K 里可打开恢复文件夹。恢复结果和失败原因显示在状态栏和提示里。 -- 回收站里的文件保持不动;每次恢复都放进新的子文件夹,不会覆盖已有文件,同名文件自动加序号。 -- 只能取回仍在回收站里的文件,不能恢复已清空回收站、格式化或被覆盖的数据。 - -## 平台与要求 - -- 支持:仅 Windows - -## 网络与数据 - -- 不联网,数据只保存在本机。 diff --git a/extensions/data-recovery/THIRD_PARTY_NOTICES.txt b/extensions/data-recovery/THIRD_PARTY_NOTICES.txt deleted file mode 100644 index 5ba79b0..0000000 --- a/extensions/data-recovery/THIRD_PARTY_NOTICES.txt +++ /dev/null @@ -1,38 +0,0 @@ -THIRD-PARTY SOFTWARE NOTICES AND INFORMATION -============================================ - -Component: ZTools Data Recovery Plugin (`data-recovery` / `lib/DataRecoveryPlugin.dll`) -Audit Date: 2026-11-27 - -This plugin bundles and invokes `lib/DataRecoveryPlugin.dll`, which statically links the following -third-party open-source components. A complete file-by-file license audit confirmed that NO GPL, -AGPL, or LGPL copyleft components are linked. - -1. The Sleuth Kit (libtsk) - - Copyright (c) 2002-2024 Brian Carrier, Basis Technology, Sleuth Kit Labs, LLC, @stake Inc., - and IBM Corporation. - - Licenses: Common Public License 1.0 (CPL-1.0) and IBM Public License 1.0 (IPL-1.0). - - Upstream source: https://github.com/sleuthkit/sleuthkit - -2. CrossGuid (`guid.h` / `guid.cpp`, bundled in libtsk) - - Copyright (c) 2014 Graeme Hill. - - License: MIT License. - -3. Apple LZVN Decompressor (`lzvn.c`, bundled in libtsk) - - Copyright (c) 2015-2016 Apple Inc. - - License: 3-Clause BSD License. - -4. Unicode UTF Conversion (`tsk_unicode.c`, bundled in libtsk) - - Copyright (c) 2001-2004 Unicode, Inc. - - License: Unicode, Inc. Permissive Redistribution License. - -5. RSA Data Security MD5 (`md5c.c`, bundled in libtsk) - - Copyright (c) 1991-1992 RSA Data Security, Inc. - - License: RSA Data Security MD5 License (permissive attribution license). - -6. SQLite (`sqlite3.c`) and Public Domain Utilities (`crc.c`, `sha1c.c`, `XGetopt.c`, `decmpfs.c`) - - License: Public Domain. - -7. JsonCpp - - Copyright (c) 2007-2010 Baptiste Lepilleur and The JsonCpp Authors. - - License: MIT License / Public Domain. diff --git a/extensions/data-recovery/icon.svg b/extensions/data-recovery/icon.svg deleted file mode 100644 index 09870e0..0000000 --- a/extensions/data-recovery/icon.svg +++ /dev/null @@ -1,3 +0,0 @@ - - - diff --git a/extensions/data-recovery/package.json b/extensions/data-recovery/package.json deleted file mode 100644 index 58e253a..0000000 --- a/extensions/data-recovery/package.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "name": "@ztools/plugin-data-recovery", - "version": "1.0.0", - "description": "列出 Windows 回收站里的文件,把勾选的文件复制到桌面的恢复文件夹", - "main": "dist/index.js", - "types": "dist/index.d.ts", - "scripts": { - "build": "tsc", - "test": "node --test tests/*.test.mjs" - }, - "dependencies": { - "@ztools/declarative-ui": "workspace:*" - } -} diff --git a/extensions/data-recovery/plugin.json b/extensions/data-recovery/plugin.json deleted file mode 100644 index 2a4fe4c..0000000 --- a/extensions/data-recovery/plugin.json +++ /dev/null @@ -1,61 +0,0 @@ -{ - "id": "data-recovery", - "name": "数据恢复", - "description": "提供快速回收站恢复(解析 $Recycle.Bin $I 元数据还原原始文件名、原路径与删除时间)与管理员级磁盘深度恢复(对接 DataRecoveryPlugin 扫描物理磁盘与分区)", - "version": "2.1.0", - "author": "ZTools Team", - "entry": "dist/index.js", - "icon": "icon.svg", - "category": [ - "文件管理", - "系统工具" - ], - "categoryId": [ - "files", - "system" - ], - "permissions": [ - "fs", - "system", - "shell" - ], - "requireAdmin": true, - "dllloader": "lib/DataRecoveryPlugin.dll", - "minAppVersion": "1.3.0.0", - "nativeComponents": [ - { - "id": "data-recovery-dll", - "kind": "dll", - "targetId": "windows-electron-any", - "arch": "ia32", - "abi": "ztools-native-host/v1", - "protocolVersion": 1, - "entry": "lib/DataRecoveryPlugin.dll" - } - ], - "targets": [ - { - "id": "windows-electron-any", - "platform": "windows", - "runtime": "electron", - "arch": "x64" - } - ], - "defaultLocale": "zh-CN", - "i18n": { - "en-US": { - "name": "Data Recovery", - "description": "Two-tier Windows data recovery: fast Recycle Bin recovery ($I v1/v2 metadata parser restoring original names, paths, and deletion times) and elevated deep disk recovery via DataRecoveryPlugin.", - "keywords": [ - "recovery", - "data recovery", - "recycle bin", - "restore", - "undelete", - "disk scan", - "files", - "windows" - ] - } - } -} diff --git a/extensions/data-recovery/src/error-i18n.ts b/extensions/data-recovery/src/error-i18n.ts deleted file mode 100644 index d97366d..0000000 --- a/extensions/data-recovery/src/error-i18n.ts +++ /dev/null @@ -1,213 +0,0 @@ -/** - * 声明式插件通用错误本地化解析器(R7 双轨平滑迁移共享底座)。 - * - * 规则: - * 1. 优先按结构化错误码(errorDetails.hostCode / details.hostCode / errorCode / code)查表: - * 先查插件传入的 codeMap,再查标准宿主错误码双语表; - * 2. 对称展示规则:中文模式(zh-CN)原文含 CJK 才直接展示,英文模式(en-US)原文不含 CJK 才直接展示, - * 既保留宿主精确本地化消息,又拦截英文技术原文裸露到中文界面、拦截中文原文裸露到英文界面; - * 3. 原文语言不匹配时优先使用标准宿主错误码译文,否则回退到插件本地 t(...) 兜底文案。 - */ - -import { getLocale } from '@ztools/declarative-ui' - -const CJK_REGEX = /[\u4e00-\u9fa5]/ - -const HOST_ERROR_CODE_MESSAGES: Record>> = { - 'zh-CN': { - INVALID_REQUEST: '请求参数无效', - METHOD_NOT_FOUND: '当前 ZTools 版本过低或不支持此接口,请升级客户端后重试', - METHOD_NOT_AVAILABLE: '当前 ZTools 版本过低或不支持此接口,请升级客户端后重试', - PERMISSION_DENIED: '权限不足,无法执行该操作', - REQUEST_TIMEOUT: '请求执行超时,请稍后重试', - CALLER_DESTROYED: '调用窗口已关闭,操作已中止', - APP_STOPPING: '应用正在退出,操作已取消', - CANCELLED: '操作已取消', - OPERATION_CANCELLED: '操作已取消', - NOT_SUPPORTED: '当前环境不支持此操作', - PLATFORM_NOT_SUPPORTED: '当前操作系统不支持此功能', - NETWORK_ERROR: '网络请求失败,请检查网络连接', - RESPONSE_TOO_LARGE: '响应数据超出大小限制', - FILE_ERROR: '文件操作失败', - FILE_NOT_FOUND: '目标文件或目录不存在', - FILE_TOO_LARGE: '文件大小超出限制', - FILE_ALREADY_EXISTS: '目标文件已存在', - DISK_FULL: '磁盘空间不足', - SHELL_ERROR: '系统命令或外部应用启动失败', - PROCESS_ERROR: '进程操作失败', - PROCESS_PROTECTED: '目标进程受系统保护,无法操作', - PROCESS_NOT_FOUND: '未找到目标进程', - PROCESS_ACCESS_DENIED: '无权访问或操作目标进程', - SCREEN_ERROR: '屏幕或窗口操作失败', - CLIPBOARD_ERROR: '剪贴板读写失败', - DATABASE_LOCKED: '本地数据库正被占用,请稍后重试', - DATABASE_KEY_NOT_FOUND: '未找到指定的数据项', - DATA_CORRUPT: '本地数据格式损坏或校验失败', - STORAGE_ERROR: '本地存储读写失败', - PLUGIN_BUSY: '插件正忙,请稍后重试', - PLUGIN_PERMISSION_REQUIRED: '插件缺少所需权限声明', - DLL_ERROR: '原生组件执行失败', - NATIVE_HOST_UNAVAILABLE: '原生宿主组件不可用', - NATIVE_HOST_ERROR: '原生宿主执行失败', - SERVICE_UNAVAILABLE: '系统提权服务不可用', - INTERNAL_ERROR: '宿主内部错误' - }, - 'en-US': { - INVALID_REQUEST: 'Invalid request parameters', - METHOD_NOT_FOUND: 'Your ZTools version is too old or does not support this API. Please upgrade and try again.', - METHOD_NOT_AVAILABLE: 'Your ZTools version is too old or does not support this API. Please upgrade and try again.', - PERMISSION_DENIED: 'Permission denied', - REQUEST_TIMEOUT: 'Request timed out. Please try again later.', - CALLER_DESTROYED: 'The caller window was closed and the operation was aborted', - APP_STOPPING: 'Application is exiting; operation cancelled', - CANCELLED: 'Operation cancelled', - OPERATION_CANCELLED: 'Operation cancelled', - NOT_SUPPORTED: 'This operation is not supported in the current environment', - PLATFORM_NOT_SUPPORTED: 'This feature is not supported on the current operating system', - NETWORK_ERROR: 'Network request failed. Please check your connection.', - RESPONSE_TOO_LARGE: 'Response payload exceeds size limit', - FILE_ERROR: 'File operation failed', - FILE_NOT_FOUND: 'Target file or directory not found', - FILE_TOO_LARGE: 'File size exceeds limit', - FILE_ALREADY_EXISTS: 'Target file already exists', - DISK_FULL: 'Insufficient disk space', - SHELL_ERROR: 'Failed to launch system command or external application', - PROCESS_ERROR: 'Process operation failed', - PROCESS_PROTECTED: 'Target process is protected by the system', - PROCESS_NOT_FOUND: 'Target process not found', - PROCESS_ACCESS_DENIED: 'Access denied for target process', - SCREEN_ERROR: 'Screen or window operation failed', - CLIPBOARD_ERROR: 'Failed to read or write clipboard', - DATABASE_LOCKED: 'Local database is locked. Please try again later.', - DATABASE_KEY_NOT_FOUND: 'Requested item was not found', - DATA_CORRUPT: 'Local data is corrupted or failed validation', - STORAGE_ERROR: 'Local storage operation failed', - PLUGIN_BUSY: 'Plugin is busy. Please try again later.', - PLUGIN_PERMISSION_REQUIRED: 'Plugin is missing required permission declaration', - DLL_ERROR: 'Native component execution failed', - NATIVE_HOST_UNAVAILABLE: 'Native host component is unavailable', - NATIVE_HOST_ERROR: 'Native host execution failed', - SERVICE_UNAVAILABLE: 'Elevated system service is unavailable', - INTERNAL_ERROR: 'Internal host error' - } -} - -function asObj(value: unknown): Record | null { - return value && typeof value === 'object' && !Array.isArray(value) - ? (value as Record) - : null -} - -function pickNonEmptyString(value: unknown): string { - return typeof value === 'string' && value.trim().length > 0 ? value.trim() : '' -} - -/** 从错误对象或宿主响应信封中提取结构化错误码(优先 errorCode,再 code) */ -export function extractErrorCode(source: unknown): string { - const rec = asObj(source) - if (!rec) return '' - const direct = pickNonEmptyString(rec.errorCode) || pickNonEmptyString(rec.code) - if (direct) return direct - const nestedErr = asObj(rec.error) - if (nestedErr) { - return pickNonEmptyString(nestedErr.errorCode) || pickNonEmptyString(nestedErr.code) - } - const nestedData = asObj(rec.data) - if (nestedData) { - return pickNonEmptyString(nestedData.errorCode) || pickNonEmptyString(nestedData.code) - } - return '' -} - -/** 从错误对象或宿主响应信封中提取 details.hostCode */ -export function extractHostCode(source: unknown): string { - const rec = asObj(source) - if (!rec) return '' - const directDetails = asObj(rec.errorDetails) || asObj(rec.details) - const fromDirect = directDetails ? pickNonEmptyString(directDetails.hostCode) : '' - if (fromDirect) return fromDirect - const nestedErr = asObj(rec.error) - if (nestedErr) { - const nestedDetails = asObj(nestedErr.errorDetails) || asObj(nestedErr.details) - const fromNested = nestedDetails ? pickNonEmptyString(nestedDetails.hostCode) : '' - if (fromNested) return fromNested - } - return '' -} - -/** 从错误对象、宿主响应或字符串中提取原始错误文案 */ -export function extractRawErrorText(source: unknown): string { - if (typeof source === 'string') return source.trim() - if (source instanceof Error) return source.message.trim() - const rec = asObj(source) - if (!rec) return '' - if ('error' in rec) { - if (typeof rec.error === 'string') return rec.error.trim() - const nestedErr = asObj(rec.error) - if (nestedErr) { - return pickNonEmptyString(nestedErr.message) || pickNonEmptyString(nestedErr.error) - } - return '' - } - return pickNonEmptyString(rec.message) -} - -/** 判断某段文本在当前 locale 下是否可直接展示给用户(对称规则:zh-CN 需含 CJK,en-US 需不含 CJK) */ -export function isDisplayableInCurrentLocale(text: string): boolean { - if (!text) return false - const locale = getLocale() - if (locale === 'zh-CN') return CJK_REGEX.test(text) - return !CJK_REGEX.test(text) -} - -/** - * 将宿主响应、异常对象或原始错误字符串安全解析为当前语言的提示文案: - * 1. 若对象属于成功响应且无 error,直接返回 fallback(避免误读成功态 message/code); - * 2. 优先按 hostCode / errorCode / code 查插件自定义 codeMap; - * 3. 若存在标准宿主错误码且无原文或原文语言不匹配,按当前语言查标准词典; - * 4. 若原始文案非空且符合当前语种(中文模式含 CJK,英文模式不含 CJK),保留原始文案; - * 5. 其余情况一律回退到插件本地传入的 fallback(即 t('...'))。 - */ -export function resolveErrorMessage( - source: unknown, - fallback: string, - codeMap?: Readonly> -): string { - if (source === null || source === undefined || source === '') { - return fallback - } - const rec = asObj(source) - if (rec && 'error' in rec && rec.ok === true && !rec.error) { - return fallback - } - - const hostCode = extractHostCode(source) - const code = extractErrorCode(source) - const rawText = extractRawErrorText(source) - - // 非失败响应容器若既无 error 文案也无 errorCode,直接返回 fallback(如 snapshot.error || t('empty')) - if (rec && 'error' in rec && !rawText && !rec.errorCode && rec.ok !== false && rec.success !== false) { - return fallback - } - - const locale = getLocale() - const dict = HOST_ERROR_CODE_MESSAGES[locale] ?? HOST_ERROR_CODE_MESSAGES['en-US'] - - if (codeMap) { - if (hostCode && codeMap[hostCode]) return codeMap[hostCode] - if (code && codeMap[code]) return codeMap[code] - } - - if (hostCode && dict[hostCode]) { - if (!rawText || !isDisplayableInCurrentLocale(rawText)) return dict[hostCode] - } - if (code && dict[code]) { - if (!rawText || !isDisplayableInCurrentLocale(rawText)) return dict[code] - } - - if (rawText && isDisplayableInCurrentLocale(rawText)) { - return rawText - } - - return fallback -} diff --git a/extensions/data-recovery/src/i18n.ts b/extensions/data-recovery/src/i18n.ts deleted file mode 100644 index f6abca6..0000000 --- a/extensions/data-recovery/src/i18n.ts +++ /dev/null @@ -1,178 +0,0 @@ -import { createTranslator } from "@ztools/declarative-ui"; - -const rawT = createTranslator( - { - "zh-CN": { - forbiddenReason: "不能向系统目录写入恢复文件,路径中也不能包含 ..", - sameDriveTargetReason: "恢复输出目录不能位于源待恢复分区({drive}:\\),请改选其他磁盘分区以免覆盖待恢复扇区数据", - notInClientMessage: "需要在 ZTools 客户端中使用", - catDocumentsName: "文档", - catDocumentsSubtitle: "Word / Excel / PPT / PDF / 文本", - catImagesName: "图片", - catImagesSubtitle: "PNG / JPG / PSD / RAW 等", - catMediaName: "视频音频", - catMediaSubtitle: "MP4 / MOV / MP3 / WAV 等", - catArchivesCodeName: "压缩包与代码", - catArchivesCodeSubtitle: "ZIP / 7z / RAR / SQL / 源代码", - catOtherName: "其他", - catOtherSubtitle: "不属于以上类型的文件", - hostNoResult: "客户端没有返回结果", - scanFailed: "读取回收站失败:{error}", - deepScanFailed: "磁盘深度扫描失败:{error}", - deviceListFailed: "读取物理磁盘列表失败:{error}", - partitionsFailed: "读取磁盘分区失败:{error}", - enumFilesFailed: "查询扫描文件列表失败:{error}", - recoverFailed: "恢复文件失败:{error}", - metadataFailed: "读取文件元数据失败:{error}", - previewFailed: "生成文件预览失败:{error}", - scanHistoryFailed: "读取扫描历史失败:{error}", - scanStatusFailed: "查询扫描状态失败:{error}", - stopScanFailed: "停止扫描失败:{error}", - desktopUnavailable: "无法获取桌面路径,不能恢复文件", - selectFilesFirst: "请先勾选要恢复的文件", - unknownFile: "(未知文件)", - invalidFilePath: "文件路径无效", - copyFailed: "复制失败", - restoreSuccessMsg: "已将 {count} 个文件 ({size}) 恢复到 {dir}", - restoreAllFailedMsg: "恢复失败,{count} 个文件均未恢复。{detail}", - restorePartialMsg: "已恢复 {okCount} 个文件到 {dir},{failCount} 个失败。{detail}", - restoreSuccessTitle: "恢复完成", - restorePartialTitle: "部分文件恢复失败", - restoreFailedTitle: "恢复失败", - openFolderFailedTitle: "无法打开恢复文件夹", - openFolderMissingHint: "{dir}(还没有恢复过文件时该文件夹可能不存在)", - desktopPathUnavailable: "无法获取桌面路径", - locateFailedTitle: "无法在资源管理器中定位此文件", - unknownTarget: "(未知)", - selectionSummary: "已勾选 {count} 项 ({size}) · 恢复到 {dir}", - recycleSummary: "快速回收站 {count} 项 ({size}) · {selection}", - deepSummary: "磁盘深度恢复 · 设备 {devices} 个 · 已发现 {count} 项 · {selection}", - crossUserPermissionWarning: "已跳过 {count} 个无权访问的其他用户回收站目录(跨用户目录需管理员权限)", - copyCheckedAction: "恢复已勾选文件 ({count} 项)", - allRecycleFiles: "全部回收站文件", - itemCount: "{count} 项", - openRecoveryFolder: "打开恢复文件夹", - filterCategoryAction: "筛选「{name}」", - deletedAtSubtitle: "原路径:{path} · 删除于 {time}", - modifiedSubtitle: "{path} · 修改于 {time}", - locateInExplorer: "在资源管理器中定位此文件", - uncheckFile: "取消勾选此文件", - checkFile: "勾选此文件", - searchPlaceholder: "搜索原始文件名、原路径或扩展名(如 .docx)...", - rescanAction: "重新扫描", - switchToDeepMode: "切换到磁盘深度恢复", - switchToRecycleMode: "切换到快速回收站", - subListTitle: "可恢复文件 ({count} 项 · 已选 {size})", - subListSubtitleRecycle: "已解析 Windows $Recycle.Bin $I 元数据,显示原始文件名与原路径;输出目录须避开源分区", - subListSubtitleDeep: "来自 DataRecoveryPlugin 物理磁盘扫描结果;恢复目标盘符必须与源待恢复分区不同", - loadingText: "正在扫描可恢复文件...", - emptyText: "当前视图下没有可恢复文件", - sectionTitle: "快速回收站(按类型)", - sectionSubtitle: "解析 $Recycle.Bin $I 原始元数据", - deepSectionTitle: "磁盘深度恢复(管理员)", - deepSectionSubtitle: "对接 DataRecoveryPlugin 扫描物理磁盘与分区", - deepDeviceSubtitle: "{type} · {size} · 卷 {volumes}", - deepStartScanAction: "深度扫描此磁盘", - deepStopScanAction: "停止当前扫描", - deepLoadHistoryAction: "查看历史扫描记录", - deepScanStartedTitle: "深度扫描已启动", - deepScanStartedMsg: "扫描任务 {scanId} 正在运行,稍后可刷新文件列表", - deepScanStoppedTitle: "已请求停止扫描", - deepNoDevicesText: "未检测到可访问的物理磁盘(请确认以管理员权限运行)", - deepVolumesUnknown: "无盘符", - deepRecoverStartedTitle: "已提交深度恢复任务", - deepRecoverStartedMsg: "正在将 {count} 个文件恢复到 {dir}" - }, - "en-US": { - forbiddenReason: "Cannot write recovered files to system directories or paths containing ..", - sameDriveTargetReason: "Recovery target directory must not be on source drive ({drive}:\\). Choose another drive to avoid overwriting recoverable sectors.", - notInClientMessage: "Requires ZTools client environment", - catDocumentsName: "Documents", - catDocumentsSubtitle: "Word / Excel / PPT / PDF / Text", - catImagesName: "Images", - catImagesSubtitle: "PNG / JPG / PSD / RAW, etc.", - catMediaName: "Media", - catMediaSubtitle: "MP4 / MOV / MP3 / WAV, etc.", - catArchivesCodeName: "Archives & Code", - catArchivesCodeSubtitle: "ZIP / 7z / RAR / SQL / Source", - catOtherName: "Other", - catOtherSubtitle: "Files outside above types", - hostNoResult: "No result returned from client", - scanFailed: "Failed to read Recycle Bin: {error}", - deepScanFailed: "Deep disk scan failed: {error}", - deviceListFailed: "Failed to list physical disks: {error}", - partitionsFailed: "Failed to read disk partitions: {error}", - enumFilesFailed: "Failed to query scanned files: {error}", - recoverFailed: "File recovery failed: {error}", - metadataFailed: "Failed to read file metadata: {error}", - previewFailed: "Failed to preview file: {error}", - scanHistoryFailed: "Failed to load scan history: {error}", - scanStatusFailed: "Failed to query scan status: {error}", - stopScanFailed: "Failed to stop scan: {error}", - desktopUnavailable: "Desktop path unavailable; cannot recover files", - selectFilesFirst: "Please select files to recover first", - unknownFile: "(Unknown file)", - invalidFilePath: "Invalid file path", - copyFailed: "Copy failed", - restoreSuccessMsg: "Recovered {count} file(s) ({size}) to {dir}", - restoreAllFailedMsg: "Recovery failed; {count} file(s) not recovered. {detail}", - restorePartialMsg: "Recovered {okCount} file(s) to {dir}, {failCount} failed. {detail}", - restoreSuccessTitle: "Recovery Complete", - restorePartialTitle: "Some Files Failed", - restoreFailedTitle: "Recovery Failed", - openFolderFailedTitle: "Unable to Open Recovery Folder", - openFolderMissingHint: "{dir} (folder may not exist before first recovery)", - desktopPathUnavailable: "Unable to resolve Desktop path", - locateFailedTitle: "Unable to reveal file in Explorer", - unknownTarget: "(Unknown)", - selectionSummary: "Checked {count} ({size}) · Target: {dir}", - recycleSummary: "Recycle Bin: {count} ({size}) · {selection}", - deepSummary: "Deep Disk Recovery · {devices} disk(s) · {count} file(s) · {selection}", - crossUserPermissionWarning: "Skipped {count} inaccessible other-user Recycle Bin folder(s) (administrator privileges required)", - copyCheckedAction: "Recover Checked Files ({count})", - allRecycleFiles: "All Recycle Bin Files", - itemCount: "{count} [[count:item|items]]", - openRecoveryFolder: "Open Recovery Folder", - filterCategoryAction: "Filter \"{name}\"", - deletedAtSubtitle: "Original: {path} · Deleted {time}", - modifiedSubtitle: "{path} · Modified {time}", - locateInExplorer: "Reveal in Folder", - uncheckFile: "Uncheck File", - checkFile: "Check File", - searchPlaceholder: "Search original filename, path, or extension (e.g. .docx)...", - rescanAction: "Rescan", - switchToDeepMode: "Switch to Deep Disk Recovery", - switchToRecycleMode: "Switch to Fast Recycle Bin", - subListTitle: "Recoverable Files ({count} · Selected {size})", - subListSubtitleRecycle: "Parsed Windows $Recycle.Bin $I metadata with original names and paths; target must differ from source drive", - subListSubtitleDeep: "Results from DataRecoveryPlugin physical disk scan; target drive must differ from source partition", - loadingText: "Scanning recoverable files...", - emptyText: "No recoverable files in this view", - sectionTitle: "Fast Recycle Bin (By Type)", - sectionSubtitle: "Parses $Recycle.Bin $I original metadata", - deepSectionTitle: "Deep Disk Recovery (Admin)", - deepSectionSubtitle: "Physical disks & partitions via DataRecoveryPlugin", - deepDeviceSubtitle: "{type} · {size} · Volumes {volumes}", - deepStartScanAction: "Deep Scan This Disk", - deepStopScanAction: "Stop Current Scan", - deepLoadHistoryAction: "Load Scan History", - deepScanStartedTitle: "Deep Scan Started", - deepScanStartedMsg: "Scan task {scanId} is running; refresh to inspect found files", - deepScanStoppedTitle: "Scan Stop Requested", - deepNoDevicesText: "No accessible physical disks detected (ensure administrator privileges)", - deepVolumesUnknown: "None", - deepRecoverStartedTitle: "Deep Recovery Started", - deepRecoverStartedMsg: "Recovering {count} file(s) to {dir}" - } - } -); - -export const t: typeof rawT = (key, params) => { - const out = rawT(key, params); - if (!out.includes("[[")) return out; - return out.replace(/\[\[([A-Za-z0-9_.-]+):([^|\]]+)\|([^\]]+)\]\]/g, (_m, k: string, one: string, other: string) => { - const v = params?.[k]; - const n = typeof v === "number" ? v : Number(String(v ?? "").replace(/,/g, "")); - return n === 1 ? one : other; - }); -}; diff --git a/extensions/data-recovery/src/index.ts b/extensions/data-recovery/src/index.ts deleted file mode 100644 index 021b5e1..0000000 --- a/extensions/data-recovery/src/index.ts +++ /dev/null @@ -1,589 +0,0 @@ -/** - * 数据恢复插件(布局二:左侧模式/分类/物理磁盘导航 + 右侧可勾选文件列表) - * - * 两级恢复模式: - * 1. 快速回收站恢复:解析 Windows $Recycle.Bin\\$I* 二进制元数据(v1/v2), - * 还原原始文件名、原始完整路径、大小与删除时间;跨用户目录权限受限时如实提示。 - * 2. 磁盘深度恢复(管理员):对接 DataRecoveryPlugin 真实 12 个导出接口, - * 扫描物理磁盘与分区,并硬校验恢复目标盘符严禁与源待恢复分区相同。 - */ - -import { - Action, - ActionPanel, - Icon, - List, - Toast, - showToast, - useEffect, - useLocale, - useState -} from "@ztools/declarative-ui"; -import { t } from "./i18n.js"; -import { resolveErrorMessage } from "./error-i18n.js"; -import { isRealElectronHost } from "./native-ipc.js"; -import { - createEmptyRecoverySnapshot, - enumScanFiles, - fetchRecoverableFiles, - formatBytes, - getDeviceList, - getNotInClientMessage, - getRecoveryCategories, - getScanHistory, - openRecoveryFolder, - recoverDeepFiles, - restoreRunFolderName, - restoreSelectedFiles, - showRecoveryItem, - startDiskScan, - stopDiskScan, - type DataRecoverySnapshot, - type DeepScannedFileItem, - type PhysicalDiskDevice, - type RecoveryCategory, - type RecoveryMode -} from "./logic.js"; - -export * from "./logic.js"; - -export function DataRecoveryCommand() { - useLocale(); - const [mode, setMode] = useState("recycle-bin"); - const [snapshot, setSnapshot] = useState(() => - isRealElectronHost() ? createEmptyRecoverySnapshot() : createEmptyRecoverySnapshot(getNotInClientMessage()) - ); - const [selectedCategory, setSelectedCategory] = useState("all"); - const [checkedIds, setCheckedIds] = useState([]); - const [searchText, setSearchText] = useState(""); - const [statusBanner, setStatusBanner] = useState(""); - const [lastOutputDir, setLastOutputDir] = useState(""); - const [isLoading, setIsLoading] = useState(isRealElectronHost()); - - // 磁盘深度恢复状态 - const [devices, setDevices] = useState([]); - const [selectedDeviceId, setSelectedDeviceId] = useState(""); - const [activeScanTaskId, setActiveScanTaskId] = useState(""); - const [activeScanId, setActiveScanId] = useState(""); - const [deepFiles, setDeepFiles] = useState([]); - const [deepError, setDeepError] = useState(""); - - const reloadRecoveryList = async () => { - setIsLoading(true); - try { - const data = await fetchRecoverableFiles(); - setSnapshot(data); - const existing = new Set(data.items.map((i) => i.id)); - setCheckedIds((prev) => prev.filter((id) => existing.has(id))); - setStatusBanner(data.permissionWarning || ""); - } finally { - setIsLoading(false); - } - }; - - const reloadDeepDevices = async () => { - setIsLoading(true); - try { - const res = await getDeviceList(); - if (!res.ok) { - setDeepError(resolveErrorMessage(res, t("deepNoDevicesText"))); - setDevices([]); - } else { - setDeepError(""); - setDevices(res.data || []); - if ((res.data || []).length > 0 && !selectedDeviceId) { - setSelectedDeviceId(res.data![0].deviceId); - } - } - } finally { - setIsLoading(false); - } - }; - - useEffect(() => { - void reloadRecoveryList(); - }, []); - - const switchMode = async (nextMode: RecoveryMode) => { - setMode(nextMode); - setCheckedIds([]); - setStatusBanner(""); - if (nextMode === "deep-disk") { - await reloadDeepDevices(); - } else { - await reloadRecoveryList(); - } - }; - - const handleStartDeepScan = async (device: PhysicalDiskDevice) => { - setSelectedDeviceId(device.deviceId); - setIsLoading(true); - try { - const taskId = `scan_${Date.now()}`; - const res = await startDiskScan({ - taskId, - deviceId: device.deviceId, - partitionNum: -1, - scanType: "quick", - scanScenario: "deleted" - }); - if (!res.ok || !res.data) { - const errMsg = resolveErrorMessage(res, t("deepScanFailed", { error: t("hostNoResult") })); - setDeepError(errMsg); - showToast({ style: Toast.Style.Failure, title: t("restoreFailedTitle"), message: errMsg }); - return; - } - setDeepError(""); - setActiveScanTaskId(taskId); - setActiveScanId(res.data.scanId); - showToast({ - style: Toast.Style.Success, - title: t("deepScanStartedTitle"), - message: t("deepScanStartedMsg", { scanId: res.data.scanId || taskId }) - }); - if (res.data.scanId) { - const enumRes = await enumScanFiles({ scanId: res.data.scanId, pageIndex: 0, pageSize: 100 }); - if (enumRes.ok && enumRes.data) { - setDeepFiles(enumRes.data.files); - } - } - } finally { - setIsLoading(false); - } - }; - - const handleStopDeepScan = async () => { - if (!activeScanTaskId) return; - const res = await stopDiskScan(activeScanTaskId); - if (res.ok) { - setActiveScanTaskId(""); - showToast({ style: Toast.Style.Success, title: t("deepScanStoppedTitle") }); - } else { - showToast({ style: Toast.Style.Failure, title: t("restoreFailedTitle"), message: res.error }); - } - }; - - const handleLoadScanHistory = async () => { - setIsLoading(true); - try { - const histRes = await getScanHistory(20); - if (!histRes.ok || !histRes.data || histRes.data.length === 0) { - setDeepError(histRes.ok ? t("emptyText") : resolveErrorMessage(histRes, t("emptyText"))); - return; - } - const latest = histRes.data[0]; - setActiveScanId(latest.scanId); - const enumRes = await enumScanFiles({ scanId: latest.scanId, pageIndex: 0, pageSize: 100 }); - if (enumRes.ok && enumRes.data) { - setDeepFiles(enumRes.data.files); - setDeepError(""); - } else { - setDeepError(enumRes.error || ""); - } - } finally { - setIsLoading(false); - } - }; - - const keyword = searchText.trim().toLowerCase(); - - const visibleRecycleItems = snapshot.items.filter((item) => { - if (selectedCategory !== "all" && item.category !== selectedCategory) return false; - if (keyword) { - const hay = `${item.name} ${item.originalPath || ""} ${item.cachePath} ${item.categoryName}`.toLowerCase(); - if (!hay.includes(keyword)) return false; - } - return true; - }); - - const visibleDeepItems = deepFiles.filter((item) => { - if (!keyword) return true; - const hay = `${item.name} ${item.path} ${item.type}`.toLowerCase(); - return hay.includes(keyword); - }); - - const checkedSet = new Set(checkedIds); - - const selectedRecycleItems = snapshot.items.filter((item) => checkedSet.has(item.id)); - const selectedDeepItems = deepFiles.filter((item) => checkedSet.has(item.fileId)); - const selectedCount = mode === "recycle-bin" ? selectedRecycleItems.length : selectedDeepItems.length; - const selectedBytes = - mode === "recycle-bin" - ? selectedRecycleItems.reduce((acc, item) => acc + item.sizeBytes, 0) - : selectedDeepItems.reduce((acc, item) => acc + item.size, 0); - - const toggleItemCheck = (id: string) => { - setCheckedIds((prev) => (prev.includes(id) ? prev.filter((i) => i !== id) : [...prev, id])); - }; - - const currentVisibleIds = - mode === "recycle-bin" ? visibleRecycleItems.map((i) => i.id) : visibleDeepItems.map((i) => i.fileId); - - const toggleAllVisible = () => { - const allChecked = currentVisibleIds.length > 0 && currentVisibleIds.every((id) => checkedSet.has(id)); - if (allChecked) { - const removeSet = new Set(currentVisibleIds); - setCheckedIds((prev) => prev.filter((id) => !removeSet.has(id))); - } else { - setCheckedIds((prev) => Array.from(new Set([...prev, ...currentVisibleIds]))); - } - }; - - const handleBatchRestore = async () => { - if (selectedCount === 0) { - showToast({ style: Toast.Style.Failure, title: t("selectFilesFirst") }); - return; - } - setIsLoading(true); - try { - if (mode === "recycle-bin") { - const res = await restoreSelectedFiles(selectedRecycleItems, snapshot.restoreTargetDir); - if (res.outputDir) setLastOutputDir(res.outputDir); - setStatusBanner(res.message); - showToast({ - style: res.ok ? Toast.Style.Success : Toast.Style.Failure, - title: res.ok ? t("restoreSuccessTitle") : res.restoredCount > 0 ? t("restorePartialTitle") : t("restoreFailedTitle"), - message: res.message - }); - } else { - const currentDevice = devices.find((d) => d.deviceId === selectedDeviceId); - const sourceDrives = currentDevice ? currentDevice.volumes : []; - const baseDir = snapshot.restoreTargetDir; - const targetPath = baseDir ? `${baseDir}\\${restoreRunFolderName()}` : ""; - const res = await recoverDeepFiles({ - taskId: `recover_${Date.now()}`, - scanId: activeScanId, - fileIds: selectedDeepItems.map((i) => i.fileId), - targetPath, - sourceDrives - }); - if (!res.ok) { - setStatusBanner(res.error || ""); - showToast({ style: Toast.Style.Failure, title: t("restoreFailedTitle"), message: res.error }); - } else { - setLastOutputDir(targetPath); - const msg = t("deepRecoverStartedMsg", { count: selectedDeepItems.length, dir: targetPath }); - setStatusBanner(msg); - showToast({ style: Toast.Style.Success, title: t("deepRecoverStartedTitle"), message: msg }); - } - } - } finally { - setIsLoading(false); - } - }; - - const openOutputFolder = async () => { - const dir = lastOutputDir || snapshot.restoreTargetDir; - const ok = await openRecoveryFolder(dir); - if (!ok) { - showToast({ - style: Toast.Style.Failure, - title: t("openFolderFailedTitle"), - message: dir ? t("openFolderMissingHint", { dir }) : t("desktopPathUnavailable") - }); - } - }; - - const locateItem = async (path: string) => { - const ok = await showRecoveryItem(path); - if (!ok) { - showToast({ style: Toast.Style.Failure, title: t("locateFailedTitle"), message: path }); - } - }; - - const selectionText = t("selectionSummary", { - count: selectedCount, - size: formatBytes(selectedBytes), - dir: snapshot.restoreTargetDir || t("unknownTarget") - }); - - const summaryText = - mode === "recycle-bin" - ? snapshot.error - ? snapshot.error - : statusBanner - ? `${statusBanner} · ${selectionText}` - : t("recycleSummary", { - count: snapshot.items.length, - size: formatBytes(snapshot.totalSizeBytes), - selection: selectionText - }) - : deepError - ? deepError - : statusBanner - ? `${statusBanner} · ${selectionText}` - : t("deepSummary", { - devices: devices.length, - count: deepFiles.length, - selection: selectionText - }); - - const restoreAction = () => - Action({ - title: t("copyCheckedAction", { count: selectedCount }), - icon: Icon.CheckCircle, - onAction: handleBatchRestore - }); - - const categories = getRecoveryCategories(); - - const recycleNavNodes = [ - List.Item({ - id: "nav-rec-all", - title: t("allRecycleFiles"), - subtitle: t("itemCount", { count: snapshot.items.length }), - icon: Icon.HardDrive, - onSelect: () => { - setMode("recycle-bin"); - setSelectedCategory("all"); - }, - accessories: [ - { tag: { value: t("itemCount", { count: snapshot.items.length }) } }, - { text: formatBytes(snapshot.totalSizeBytes) } - ], - actions: ActionPanel({ - children: [ - restoreAction(), - Action({ - title: t("openRecoveryFolder"), - icon: Icon.Folder, - onAction: openOutputFolder - }) - ] - }) - }), - ...categories.map((cat) => { - const catItems = snapshot.items.filter((i) => i.category === cat.id); - const catBytes = catItems.reduce((s, i) => s + i.sizeBytes, 0); - const ratio = Math.min(1, catBytes / Math.max(1, snapshot.totalSizeBytes)); - - return List.Item({ - id: `nav-rec-${cat.id}`, - title: cat.name, - subtitle: cat.subtitle, - icon: Icon.Document, - onSelect: () => { - setMode("recycle-bin"); - setSelectedCategory(cat.id); - }, - accessories: [ - { progress: ratio }, - { tag: { value: t("itemCount", { count: catItems.length }) } }, - { text: formatBytes(catBytes) } - ], - actions: ActionPanel({ - children: [ - Action({ - title: t("filterCategoryAction", { name: cat.name }), - icon: Icon.Filter, - onAction: () => { - setMode("recycle-bin"); - setSelectedCategory(cat.id); - } - }), - restoreAction() - ] - }) - }); - }) - ]; - - const deepNavNodes = - devices.length > 0 - ? devices.map((device) => - List.Item({ - id: `nav-disk-${device.deviceId}`, - title: device.name, - subtitle: t("deepDeviceSubtitle", { - type: device.type, - size: formatBytes(device.size), - volumes: device.volumes.length > 0 ? device.volumes.map((v) => `${v}:`).join(", ") : t("deepVolumesUnknown") - }), - icon: Icon.HardDrive, - onSelect: () => { - setMode("deep-disk"); - setSelectedDeviceId(device.deviceId); - }, - actions: ActionPanel({ - children: [ - Action({ - title: t("deepStartScanAction"), - icon: Icon.MagnifyingGlass, - onAction: () => handleStartDeepScan(device) - }), - ...(activeScanTaskId - ? [ - Action({ - title: t("deepStopScanAction"), - icon: Icon.Stop, - onAction: handleStopDeepScan - }) - ] - : []), - Action({ - title: t("deepLoadHistoryAction"), - icon: Icon.Clock, - onAction: handleLoadScanHistory - }) - ] - }) - }) - ) - : [ - List.Item({ - id: "nav-disk-empty", - title: t("deepSectionTitle"), - subtitle: deepError || t("deepNoDevicesText"), - icon: Icon.HardDrive, - onSelect: () => void switchMode("deep-disk"), - actions: ActionPanel({ - children: [ - Action({ - title: t("rescanAction"), - icon: Icon.ArrowClockwise, - onAction: () => void reloadDeepDevices() - }), - Action({ - title: t("deepLoadHistoryAction"), - icon: Icon.Clock, - onAction: handleLoadScanHistory - }) - ] - }) - }) - ]; - - const subListItems = - mode === "recycle-bin" - ? visibleRecycleItems.map((item) => { - const isChecked = checkedSet.has(item.id); - const subtitle = - item.originalPath && item.deletedAtText - ? t("deletedAtSubtitle", { path: item.originalPath, time: item.deletedAtText }) - : item.originalPath - ? item.originalPath - : item.modifiedText - ? t("modifiedSubtitle", { path: item.cachePath, time: item.modifiedText }) - : item.cachePath; - - return List.Item({ - id: `rec-item-${item.id}`, - title: item.name, - subtitle, - icon: Icon.Document, - checkable: true, - checked: isChecked, - onCheckChange: () => toggleItemCheck(item.id), - onToggleCheck: () => toggleItemCheck(item.id), - accessories: [{ tag: { value: item.categoryName } }, { text: formatBytes(item.sizeBytes) }], - actions: ActionPanel({ - children: [ - restoreAction(), - Action({ - title: t("locateInExplorer"), - icon: Icon.Folder, - onAction: () => locateItem(item.cachePath) - }), - Action({ - title: isChecked ? t("uncheckFile") : t("checkFile"), - icon: Icon.CheckCircle, - onAction: () => toggleItemCheck(item.id) - }), - Action({ - title: t("openRecoveryFolder"), - icon: Icon.Folder, - onAction: openOutputFolder - }) - ] - }) - }); - }) - : visibleDeepItems.map((item) => { - const isChecked = checkedSet.has(item.fileId); - return List.Item({ - id: `deep-item-${item.fileId}`, - title: item.name, - subtitle: item.path, - icon: Icon.Document, - checkable: true, - checked: isChecked, - onCheckChange: () => toggleItemCheck(item.fileId), - onToggleCheck: () => toggleItemCheck(item.fileId), - accessories: [{ tag: { value: item.type } }, { text: formatBytes(item.size) }], - actions: ActionPanel({ - children: [ - restoreAction(), - Action({ - title: isChecked ? t("uncheckFile") : t("checkFile"), - icon: Icon.CheckCircle, - onAction: () => toggleItemCheck(item.fileId) - }), - Action({ - title: t("openRecoveryFolder"), - icon: Icon.Folder, - onAction: openOutputFolder - }) - ] - }) - }); - }); - - const allChecked = currentVisibleIds.length > 0 && currentVisibleIds.every((id) => checkedSet.has(id)); - const someChecked = currentVisibleIds.some((id) => checkedSet.has(id)); - - return List({ - isLoading, - searchBarPlaceholder: t("searchPlaceholder"), - onSearchTextChange: setSearchText, - isShowingDetail: false, - filterBar: { - summaryText, - actions: [ - { - id: "toggle-mode", - title: mode === "recycle-bin" ? t("switchToDeepMode") : t("switchToRecycleMode"), - style: "secondary", - onAction: () => { - void switchMode(mode === "recycle-bin" ? "deep-disk" : "recycle-bin"); - } - }, - { - id: "rescan", - title: t("rescanAction"), - style: "secondary", - onAction: () => { - if (mode === "recycle-bin") { - void reloadRecoveryList(); - } else { - void reloadDeepDevices(); - } - } - } - ] - }, - subList: { - title: t("subListTitle", { count: currentVisibleIds.length, size: formatBytes(selectedBytes) }), - subtitle: mode === "recycle-bin" ? t("subListSubtitleRecycle") : t("subListSubtitleDeep"), - emptyText: - (mode === "recycle-bin" ? snapshot.error : deepError) || (isLoading ? t("loadingText") : t("emptyText")), - checkable: currentVisibleIds.length > 0, - checked: allChecked ? true : someChecked ? "indeterminate" : false, - onCheckChange: () => toggleAllVisible(), - items: subListItems - }, - children: [ - List.Section({ - title: t("sectionTitle"), - subtitle: t("sectionSubtitle"), - children: recycleNavNodes - }), - List.Section({ - title: t("deepSectionTitle"), - subtitle: t("deepSectionSubtitle"), - children: deepNavNodes - }) - ] - }); -} - -export default DataRecoveryCommand; diff --git a/extensions/data-recovery/src/logic.ts b/extensions/data-recovery/src/logic.ts deleted file mode 100644 index 1b67544..0000000 --- a/extensions/data-recovery/src/logic.ts +++ /dev/null @@ -1,1059 +0,0 @@ -import { getLocale } from "@ztools/declarative-ui"; -import { t } from "./i18n.js"; -import { - callHostTransport, - formatBytes, - getRealSystemPath, - invokePluginService, - isRealElectronHost, - openRealPath, - probeRealDiskDrives, - showRealItemInFolder, - type NativeInvocationResult -} from "./native-ipc.js"; -import { resolveErrorMessage } from "./error-i18n.js"; -import { - FORBIDDEN_TARGET_PATTERN, - decodeBase64ToBytes, - extractDriveLetter, - filetimeToUnixMs, - parseRecycleBinInfoFile, - validateRecoveryOutputTarget, - type ParsedRecycleBinInfo, - type RecoveryTargetValidationResult -} from "./recycle-bin.js"; - -type DynamicBridge = ReturnType; - -export { - FORBIDDEN_TARGET_PATTERN, - decodeBase64ToBytes, - extractDriveLetter, - filetimeToUnixMs, - formatBytes, - parseRecycleBinInfoFile, - validateRecoveryOutputTarget -}; -export type { NativeInvocationResult, ParsedRecycleBinInfo, RecoveryTargetValidationResult }; - -export const DATA_RECOVERY_DLL_PLUGIN = "DataRecoveryPlugin"; - -/** DataRecoveryPlugin.dll 真实导出的全部 12 个业务函数白名单 */ -export const DATA_RECOVERY_DLL_FUNCTIONS = [ - "GetDeviceList", - "GetDeviceListAsync", - "GetPartitions", - "StartScan", - "StopScan", - "EnumFiles", - "EnumFilesAsync", - "RecoverFile", - "GetFileMetadata", - "PreviewFile", - "GetScanStatus", - "GetScanHistory" -] as const; - -export type DataRecoveryDllFunctionName = (typeof DATA_RECOVERY_DLL_FUNCTIONS)[number]; -export type RecoveryMode = "recycle-bin" | "deep-disk"; - -export function getNotInClientMessage(): string { - return t("notInClientMessage"); -} -export function getForbiddenReason(): string { - return t("forbiddenReason"); -} -export const RESTORE_FOLDER_NAME = "ZToolsRecovered"; - -export type RecoveryCategory = "all" | "documents" | "images" | "media" | "archives_code" | "other"; - -export interface RecoveryCategoryMeta { - id: Exclude; - name: string; - subtitle: string; - exts: string[]; -} - -const CATEGORY_DEFS: Array<{ - id: Exclude; - nameKey: "catDocumentsName" | "catImagesName" | "catMediaName" | "catArchivesCodeName" | "catOtherName"; - subtitleKey: - | "catDocumentsSubtitle" - | "catImagesSubtitle" - | "catMediaSubtitle" - | "catArchivesCodeSubtitle" - | "catOtherSubtitle"; - exts: string[]; -}> = [ - { - id: "documents", - nameKey: "catDocumentsName", - subtitleKey: "catDocumentsSubtitle", - exts: [".docx", ".doc", ".xlsx", ".xls", ".pptx", ".ppt", ".pdf", ".md", ".txt", ".csv", ".wps"] - }, - { - id: "images", - nameKey: "catImagesName", - subtitleKey: "catImagesSubtitle", - exts: [".png", ".jpg", ".jpeg", ".webp", ".gif", ".bmp", ".psd", ".svg", ".raw", ".cr2", ".heic"] - }, - { - id: "media", - nameKey: "catMediaName", - subtitleKey: "catMediaSubtitle", - exts: [".mp4", ".mov", ".mkv", ".avi", ".mp3", ".wav", ".flac", ".m4a"] - }, - { - id: "archives_code", - nameKey: "catArchivesCodeName", - subtitleKey: "catArchivesCodeSubtitle", - exts: [".zip", ".7z", ".rar", ".tar", ".gz", ".sql", ".json", ".ts", ".js", ".py"] - }, - { - id: "other", - nameKey: "catOtherName", - subtitleKey: "catOtherSubtitle", - exts: [] - } -]; - -export function getRecoveryCategories(): RecoveryCategoryMeta[] { - return CATEGORY_DEFS.map((c) => ({ - id: c.id, - name: t(c.nameKey), - subtitle: t(c.subtitleKey), - exts: c.exts - })); -} - -export interface RecoverableFileItem { - id: string; - /** 优先为 $I 元数据还原后的原始文件名,无法读取 $I 时回退回收站内部 $R 文件名 */ - name: string; - /** 文件在回收站中的真实实体路径($R*) */ - cachePath: string; - /** 对应的 $I 元数据文件路径(存在时提供) */ - infoFilePath?: string; - /** 从 $I 解析出的原始完整路径 */ - originalPath?: string; - /** 源所在盘符(大写,如 "C") */ - sourceDrive?: string; - category: Exclude; - categoryName: string; - sizeBytes: number; - /** 删除时间(源自 $I FILETIME,无则为空) */ - deletedAtMs?: number; - deletedAtText?: string; - /** 文件修改时间或删除时间展示文本 */ - modifiedText: string; - /** 元数据解析状态:parsed=成功解析 $I,raw=未配对或 $I 损坏 */ - metadataStatus: "parsed" | "raw"; -} - -export interface DataRecoverySnapshot { - /** 推荐恢复目录(自动优先避开与源回收站相同的系统盘);桌面不可用时为空 */ - restoreTargetDir: string; - items: RecoverableFileItem[]; - totalSizeBytes: number; - updatedAt: string; - /** 跨用户 SID 目录因普通权限被拒绝时如实记录 */ - inaccessibleSids: string[]; - permissionWarning?: string; - error?: string; -} - -export interface RestoreFailure { - name: string; - error: string; - errorCode?: string; -} - -export interface RestoreResult { - ok: boolean; - restoredCount: number; - restoredBytes: number; - restoredPaths: string[]; - failed: RestoreFailure[]; - outputDir: string; - message: string; -} - -// ============================================================================ -// 磁盘深度恢复(DataRecoveryPlugin 12 个真实导出函数)类型定义 -// ============================================================================ - -export interface PhysicalDiskDevice { - deviceId: string; - name: string; - size: number; - type: string; - status: string; - fileSystem: string; - volumes: string[]; -} - -export interface DiskPartitionInfo { - partitionNum: number; - start: number; - length: number; - description: string; - type: string; - fileSystem: string; - allocated: boolean; - driveLetter: string; -} - -export interface DeepScannedFileItem { - fileId: string; - id: number; - name: string; - path: string; - size: number; - type: string; - recoverable: boolean; - integrity: string; - isDeleted: boolean; -} - -export interface DeepScanHistoryItem { - scanId: string; - deviceId: string; - deviceName: string; - partitionNum: number; - scanType: string; - scanScenario: string; - startTime: number; - endTime: number | null; - totalFiles: number; - totalSize: number; - status: string; - description: string; - cacheAvailable: boolean; -} - -export interface DeepCallResult { - ok: boolean; - data?: T; - error?: string; - errorCode?: string; -} - -export function createEmptyRecoverySnapshot(error?: string): DataRecoverySnapshot { - return { - restoreTargetDir: "", - items: [], - totalSizeBytes: 0, - updatedAt: "", - inaccessibleSids: [], - ...(error ? { error } : {}) - }; -} - -export function classifyRecoveryExt(extRaw: string): RecoveryCategoryMeta { - const ext = String(extRaw || "").toLowerCase(); - const categories = getRecoveryCategories(); - for (const cat of categories) { - if (cat.exts.includes(ext)) return cat; - } - return categories.find((c) => c.id === "other")!; -} - -function hasClientHost(hostBridge?: DynamicBridge): boolean { - return Boolean(hostBridge) || isRealElectronHost(); -} - -function errorText(err: unknown): string { - return err instanceof Error ? err.message : String(err); -} - -function isAccessDeniedError(error?: string, errorCode?: string): boolean { - const code = String(errorCode || "").toUpperCase(); - if (code === "PERMISSION_DENIED" || code === "EACCES" || code === "EPERM" || code === "ACCESS_DENIED") { - return true; - } - const msg = String(error || ""); - return /EACCES|EPERM|access\s*denied|permission\s*denied/i.test(msg); -} - -function formatTimestampMs(ms: number): string { - if (!Number.isFinite(ms) || ms <= 0) return ""; - return new Date(ms).toLocaleString(getLocale()); -} - -function formatModified(raw: DynamicBridge): string { - const iso = typeof raw?.modifiedAt === "string" ? Date.parse(raw.modifiedAt) : NaN; - const ms = Number.isFinite(iso) ? iso : Number(raw?.deletedAtMs); - if (!Number.isFinite(ms) || ms <= 0) return ""; - return new Date(ms).toLocaleString(getLocale()); -} - -interface RawDirEntry { - name: string; - path: string; - isDirectory: boolean; - sizeBytes: number; - modifiedAtMs: number; -} - -function normalizeDirEntries(parentDir: string, payload: DynamicBridge): RawDirEntry[] { - const rawList: DynamicBridge[] = Array.isArray(payload) - ? payload - : Array.isArray(payload?.entries) - ? payload.entries - : Array.isArray(payload?.items) - ? payload.items - : Array.isArray(payload?.files) - ? payload.files - : []; - const base = parentDir.replace(/[\\/]+$/, ""); - const entries: RawDirEntry[] = []; - for (const item of rawList) { - if (!item || typeof item !== "object") continue; - const rawName = String(item.name || item.fileName || "").trim(); - const rawPath = String(item.path || item.fullPath || (rawName ? `${base}\\${rawName}` : "")).trim(); - const name = rawName || rawPath.split(/[\\/]/).pop() || ""; - if (!name || !rawPath) continue; - const isDirectory = Boolean(item.isDirectory ?? item.isDir ?? item.is_dir ?? item.type === "directory"); - const sizeNum = Number(item.sizeBytes ?? item.size ?? 0); - const iso = typeof item.modifiedAt === "string" ? Date.parse(item.modifiedAt) : NaN; - const rawMtime = Number(item.mtimeMs ?? item.mtime ?? 0); - const modifiedAtMs = Number.isFinite(iso) ? iso : Number.isFinite(rawMtime) && rawMtime > 0 ? rawMtime : 0; - entries.push({ - name, - path: rawPath, - isDirectory, - sizeBytes: Number.isFinite(sizeNum) && sizeNum >= 0 ? sizeNum : 0, - modifiedAtMs - }); - } - return entries; -} - -function extractBase64Content(payload: DynamicBridge): string { - if (typeof payload === "string") return payload; - if (payload && typeof payload === "object") { - if (typeof payload.content === "string") return payload.content; - if (typeof payload.data === "string") return payload.data; - if (typeof payload.base64 === "string") return payload.base64; - } - return ""; -} - -/** - * 模式 ①:快速回收站恢复扫描。 - * 遍历各盘符 `$Recycle.Bin\`,配对读取 `$I*` 二进制头(v1/v2)还原原始文件名、原完整路径、 - * 原始大小与 FILETIME 删除时间;跨用户 SID 目录遇权限拒绝时如实记录并提示需管理员权限,绝不造假。 - */ -export async function scanRecycleBinFast( - hostBridge?: DynamicBridge, - driveLetters?: string[] -): Promise { - if (!hasClientHost(hostBridge)) { - return createEmptyRecoverySnapshot(getNotInClientMessage()); - } - - try { - const desktop = await getRealSystemPath("desktop", hostBridge); - const restoreTargetDir = desktop ? `${desktop.replace(/[\\/]+$/, "")}\\${RESTORE_FOLDER_NAME}` : ""; - - let candidateDrives: string[] = []; - if (Array.isArray(driveLetters) && driveLetters.length > 0) { - candidateDrives = driveLetters - .map((d) => extractDriveLetter(d)) - .filter((d): d is string => Boolean(d)); - } else { - const probed = await probeRealDiskDrives(["C", "D", "E", "F", "G"], hostBridge); - candidateDrives = probed - .map((d) => extractDriveLetter(d.drive)) - .filter((d): d is string => Boolean(d)); - if (candidateDrives.length === 0) { - candidateDrives = ["C", "D", "E"]; - } - } - candidateDrives = Array.from(new Set(candidateDrives)); - - const items: RecoverableFileItem[] = []; - const seen = new Set(); - const inaccessibleSids: string[] = []; - let readSuccessDrives = 0; - let firstFatalError = ""; - - for (const drive of candidateDrives) { - const recycleRoot = `${drive}:\\$Recycle.Bin`; - const rootRes = await callHostTransport( - "filesystem_get_directory_contents", - { path: recycleRoot }, - hostBridge - ); - - if (!rootRes.ok) { - if (isAccessDeniedError(rootRes.error, rootRes.errorCode)) { - inaccessibleSids.push(recycleRoot); - } else if (!firstFatalError && rootRes.errorCode !== "FILE_NOT_FOUND" && !/ENOENT|not\s*found/i.test(String(rootRes.error || ""))) { - firstFatalError = resolveErrorMessage(rootRes, t("hostNoResult")); - } - continue; - } - - readSuccessDrives += 1; - const sidDirs = normalizeDirEntries(recycleRoot, rootRes.data).filter( - (entry) => entry.isDirectory && /^S-1-/i.test(entry.name) - ); - - for (const sidDir of sidDirs) { - const sidRes = await callHostTransport( - "filesystem_get_directory_contents", - { path: sidDir.path }, - hostBridge - ); - if (!sidRes.ok) { - if (isAccessDeniedError(sidRes.error, sidRes.errorCode)) { - inaccessibleSids.push(sidDir.path); - } - continue; - } - - const dirEntries = normalizeDirEntries(sidDir.path, sidRes.data); - const infoBySuffix = new Map(); - const dataEntries: RawDirEntry[] = []; - - for (const entry of dirEntries) { - if (entry.name.startsWith("$I") && !entry.isDirectory) { - infoBySuffix.set(entry.name.slice(2).toLowerCase(), entry); - } else if (entry.name.startsWith("$R")) { - dataEntries.push(entry); - } - } - - for (const dataEntry of dataEntries) { - const dedupKey = dataEntry.path.toLowerCase(); - if (seen.has(dedupKey)) continue; - seen.add(dedupKey); - - const suffixKey = dataEntry.name.slice(2).toLowerCase(); - const infoEntry = infoBySuffix.get(suffixKey); - - let displayName = dataEntry.name; - let originalPath: string | undefined; - let sizeBytes = dataEntry.sizeBytes; - let deletedAtMs = 0; - let metadataStatus: "parsed" | "raw" = "raw"; - - if (infoEntry) { - const readInfoRes = await callHostTransport( - "filesystem_read_file", - { path: infoEntry.path, encoding: "base64" }, - hostBridge - ); - if (readInfoRes.ok) { - const b64 = extractBase64Content(readInfoRes.data); - const rawBytes = decodeBase64ToBytes(b64); - if (rawBytes) { - const parsed = parseRecycleBinInfoFile(rawBytes); - if (parsed.ok) { - displayName = parsed.originalName; - originalPath = parsed.originalPath; - if (parsed.originalSizeBytes >= 0) { - sizeBytes = parsed.originalSizeBytes; - } - deletedAtMs = parsed.deletedAtMs; - metadataStatus = "parsed"; - } - } - } - } - - const extMatch = displayName.match(/\.[^.\\/]+$/); - const cat = classifyRecoveryExt(extMatch ? extMatch[0] : ""); - const deletedAtText = deletedAtMs > 0 ? formatTimestampMs(deletedAtMs) : ""; - const modifiedText = deletedAtText || (dataEntry.modifiedAtMs > 0 ? formatTimestampMs(dataEntry.modifiedAtMs) : ""); - - items.push({ - id: `rb_${drive}_${items.length}`, - name: displayName, - cachePath: dataEntry.path, - ...(infoEntry ? { infoFilePath: infoEntry.path } : {}), - ...(originalPath ? { originalPath } : {}), - sourceDrive: drive, - category: cat.id, - categoryName: cat.name, - sizeBytes: Math.max(0, sizeBytes), - ...(deletedAtMs > 0 ? { deletedAtMs, deletedAtText } : {}), - modifiedText, - metadataStatus - }); - } - } - } - - const permissionWarning = - inaccessibleSids.length > 0 - ? t("crossUserPermissionWarning", { count: inaccessibleSids.length }) - : undefined; - - if (readSuccessDrives === 0 && inaccessibleSids.length === 0 && firstFatalError) { - return { - ...createEmptyRecoverySnapshot(t("scanFailed", { error: firstFatalError })), - restoreTargetDir - }; - } - - return { - restoreTargetDir, - items, - totalSizeBytes: items.reduce((sum, item) => sum + item.sizeBytes, 0), - updatedAt: new Date().toLocaleTimeString(getLocale()), - inaccessibleSids, - ...(permissionWarning ? { permissionWarning } : {}), - ...(restoreTargetDir ? {} : { error: t("desktopUnavailable") }) - }; - } catch (err) { - return createEmptyRecoverySnapshot(t("scanFailed", { error: errorText(err) })); - } -} - -export const fetchRecoverableFiles = scanRecycleBinFast; -export const scanRecoverableFiles = scanRecycleBinFast; - -function pad(n: number, width = 2): string { - return String(n).padStart(width, "0"); -} - -/** 本次恢复使用的新子文件夹名,例如 20261028-153012-045 */ -export function restoreRunFolderName(now: Date = new Date()): string { - return `${now.getFullYear()}${pad(now.getMonth() + 1)}${pad(now.getDate())}-${pad(now.getHours())}${pad( - now.getMinutes() - )}${pad(now.getSeconds())}-${pad(now.getMilliseconds(), 3)}`; -} - -/** 同一次恢复里文件名重复时追加序号,保证不互相覆盖 */ -function uniqueName(name: string, used: Set): string { - const lower = name.toLowerCase(); - if (!used.has(lower)) { - used.add(lower); - return name; - } - const dot = name.lastIndexOf("."); - const stem = dot > 0 ? name.slice(0, dot) : name; - const ext = dot > 0 ? name.slice(dot) : ""; - for (let i = 2; ; i += 1) { - const candidate = `${stem} (${i})${ext}`; - if (!used.has(candidate.toLowerCase())) { - used.add(candidate.toLowerCase()); - return candidate; - } - } -} - -/** - * 恢复选中的回收站文件: - * - 硬校验输出目录严禁位于系统目录或源待恢复文件所在分区; - * - 逐个通过宿主 `filesystem_copy_file` 复制到带时间戳的新建子文件夹,不删除回收站原文件。 - */ -export async function restoreSelectedFiles( - items: RecoverableFileItem[], - restoreDir: string, - hostOverride?: DynamicBridge, - now: Date = new Date() -): Promise { - const baseDir = String(restoreDir || "").trim().replace(/[\\/]+$/, ""); - const empty = (message: string): RestoreResult => ({ - ok: false, - restoredCount: 0, - restoredBytes: 0, - restoredPaths: [], - failed: [], - outputDir: "", - message - }); - - if (!items || items.length === 0) return empty(t("selectFilesFirst")); - - const sourceDrives = items - .map((item) => item.sourceDrive || extractDriveLetter(item.cachePath) || "") - .filter(Boolean); - - const targetCheck = validateRecoveryOutputTarget(sourceDrives, baseDir); - if (!targetCheck.ok) { - return empty(targetCheck.error || getForbiddenReason()); - } - - const outputDir = `${baseDir}\\${restoreRunFolderName(now)}`; - await callHostTransport("filesystem_create_directory", { path: outputDir }, hostOverride); - - const used = new Set(); - const restoredPaths: string[] = []; - const failed: RestoreFailure[] = []; - let restoredBytes = 0; - - for (const item of items) { - const src = String(item?.cachePath || "").trim(); - const name = String(item?.name || "").trim(); - if (!src || !name || /[\\/]/.test(name) || name === "." || name === "..") { - failed.push({ name: name || src || t("unknownFile"), error: t("invalidFilePath") }); - continue; - } - if (FORBIDDEN_TARGET_PATTERN.test(src)) { - failed.push({ name, error: getForbiddenReason() }); - continue; - } - - const perItemDriveCheck = validateRecoveryOutputTarget(src, outputDir); - if (!perItemDriveCheck.ok) { - failed.push({ - name, - error: perItemDriveCheck.error || getForbiddenReason(), - ...(perItemDriveCheck.errorCode ? { errorCode: perItemDriveCheck.errorCode } : {}) - }); - continue; - } - - const dest = `${outputDir}\\${uniqueName(name, used)}`; - const copyRes = await callHostTransport( - "filesystem_copy_file", - { sourcePath: src, destPath: dest }, - hostOverride - ); - if (copyRes.ok) { - restoredPaths.push(dest); - restoredBytes += item.sizeBytes; - } else { - failed.push({ name, error: resolveErrorMessage(copyRes, t("copyFailed")) }); - } - } - - const failureText = failed[0] ? `${failed[0].name}: ${failed[0].error}` : ""; - let message: string; - if (failed.length === 0) { - message = t("restoreSuccessMsg", { - count: restoredPaths.length, - size: formatBytes(restoredBytes), - dir: outputDir - }); - } else if (restoredPaths.length === 0) { - message = t("restoreAllFailedMsg", { count: failed.length, detail: failureText }); - } else { - message = t("restorePartialMsg", { - okCount: restoredPaths.length, - dir: outputDir, - failCount: failed.length, - detail: failureText - }); - } - - return { - ok: failed.length === 0, - restoredCount: restoredPaths.length, - restoredBytes, - restoredPaths, - failed, - outputDir: restoredPaths.length > 0 ? outputDir : "", - message - }; -} - -// ============================================================================ -// 模式 ②:磁盘深度恢复 —— 对接 DataRecoveryPlugin 全部 12 个真实导出函数 -// ============================================================================ - -async function callDataRecoveryDll( - func: DataRecoveryDllFunctionName, - params: Record, - fallbackErrorKey: - | "deviceListFailed" - | "partitionsFailed" - | "deepScanFailed" - | "stopScanFailed" - | "enumFilesFailed" - | "recoverFailed" - | "metadataFailed" - | "previewFailed" - | "scanStatusFailed" - | "scanHistoryFailed", - hostOverride?: DynamicBridge, - useCallbackChannel = false -): Promise> { - if (!hasClientHost(hostOverride)) { - return { ok: false, error: getNotInClientMessage(), errorCode: "NO_HOST" }; - } - - if (useCallbackChannel) { - const cbRes = await callHostTransport( - "dllplugin_call_with_callback", - { plugin: DATA_RECOVERY_DLL_PLUGIN, func, params }, - hostOverride - ); - if (!cbRes.ok) { - const msg = resolveErrorMessage(cbRes, t("hostNoResult")); - return { - ok: false, - error: t(fallbackErrorKey, { error: msg }), - ...(cbRes.errorCode ? { errorCode: cbRes.errorCode } : {}) - }; - } - const inner = cbRes.data; - if (inner && typeof inner === "object" && (inner.success === false || inner.ok === false)) { - const msg = resolveErrorMessage(inner, t("hostNoResult")); - return { - ok: false, - error: t(fallbackErrorKey, { error: msg }), - ...(typeof inner.errorCode === "string" ? { errorCode: inner.errorCode } : {}) - }; - } - return { ok: true, data: inner as T }; - } - - const res = await invokePluginService(DATA_RECOVERY_DLL_PLUGIN, func, params, hostOverride); - if (!res.ok || (res.data && typeof res.data === "object" && (res.data.success === false || res.data.ok === false))) { - const errSource = res.data && typeof res.data === "object" && res.data.error ? res.data : res; - const msg = resolveErrorMessage(errSource, t("hostNoResult")); - const code = - typeof res.data?.errorCode === "string" - ? res.data.errorCode - : res.errorCode; - return { - ok: false, - error: t(fallbackErrorKey, { error: msg }), - ...(code ? { errorCode: code } : {}) - }; - } - return { ok: true, data: res.data as T }; -} - -/** 1/12: GetDeviceList(同步获取物理磁盘与卷列表) */ -export async function getDeviceList(hostOverride?: DynamicBridge): Promise> { - const res = await callDataRecoveryDll("GetDeviceList", {}, "deviceListFailed", hostOverride, false); - if (!res.ok) return { ok: false, error: res.error, errorCode: res.errorCode }; - const rawDevices: DynamicBridge[] = Array.isArray(res.data?.devices) ? res.data.devices : []; - const devices: PhysicalDiskDevice[] = rawDevices - .filter((d) => d && typeof d === "object" && typeof d.deviceId === "string" && d.deviceId.trim().length > 0) - .map((d) => ({ - deviceId: String(d.deviceId), - name: String(d.name || d.deviceId), - size: Math.max(0, Number(d.size ?? 0) || 0), - type: String(d.type || "other"), - status: String(d.status || "normal"), - fileSystem: String(d.fileSystem || ""), - volumes: Array.isArray(d.volumes) - ? d.volumes - .map((v: DynamicBridge) => (typeof v === "string" ? v : String(v?.letter || ""))) - .map((v: string) => extractDriveLetter(v) || "") - .filter(Boolean) - : [] - })); - return { ok: true, data: devices }; -} - -/** 2/12: GetDeviceListAsync(带回调异步获取物理磁盘列表) */ -export async function getDeviceListAsync( - taskId: string, - hostOverride?: DynamicBridge -): Promise> { - return callDataRecoveryDll( - "GetDeviceListAsync", - { taskId }, - "deviceListFailed", - hostOverride, - true - ); -} - -/** 3/12: GetPartitions(读取指定物理磁盘的分区列表) */ -export async function getPartitions( - deviceId: string, - hostOverride?: DynamicBridge -): Promise> { - const res = await callDataRecoveryDll( - "GetPartitions", - { deviceId }, - "partitionsFailed", - hostOverride, - false - ); - if (!res.ok) return { ok: false, error: res.error, errorCode: res.errorCode }; - const rawList: DynamicBridge[] = Array.isArray(res.data?.partitions) ? res.data.partitions : []; - const partitions: DiskPartitionInfo[] = rawList - .filter((p) => p && typeof p === "object") - .map((p) => ({ - partitionNum: typeof p.partitionNum === "number" && Number.isFinite(p.partitionNum) ? p.partitionNum : -1, - start: Math.max(0, Number(p.start ?? 0) || 0), - length: Math.max(0, Number(p.length ?? 0) || 0), - description: String(p.description || ""), - type: String(p.type || ""), - fileSystem: String(p.fileSystem || ""), - allocated: Boolean(p.allocated), - driveLetter: extractDriveLetter(String(p.driveLetter || "")) || "" - })); - return { ok: true, data: partitions }; -} - -/** 4/12: StartScan(启动物理磁盘或指定分区的深度扫描任务) */ -export async function startDiskScan( - params: { - taskId: string; - deviceId: string; - partitionNum?: number; - scanType?: "quick" | "deep" | "raw"; - scanScenario?: string; - }, - hostOverride?: DynamicBridge -): Promise> { - const partitionNum = - typeof params.partitionNum === "number" && Number.isFinite(params.partitionNum) ? params.partitionNum : -1; - const payload = { - taskId: params.taskId, - deviceId: params.deviceId, - partitionNum, - scanType: params.scanType || "quick", - scanScenario: params.scanScenario || "deleted" - }; - const res = await callDataRecoveryDll("StartScan", payload, "deepScanFailed", hostOverride, true); - if (!res.ok) return { ok: false, error: res.error, errorCode: res.errorCode }; - return { - ok: true, - data: { - scanId: String(res.data?.scanId || ""), - taskId: params.taskId - } - }; -} - -/** 5/12: StopScan(停止指定扫描任务) */ -export async function stopDiskScan( - taskId: string, - hostOverride?: DynamicBridge -): Promise> { - const res = await callDataRecoveryDll("StopScan", { taskId }, "stopScanFailed", hostOverride, false); - if (!res.ok) return { ok: false, error: res.error, errorCode: res.errorCode }; - return { ok: true, data: { message: String(res.data?.message || "Scan stopped") } }; -} - -function parseDeepFileRows(data: DynamicBridge): { files: DeepScannedFileItem[]; totalCount: number } { - const rawFiles: DynamicBridge[] = Array.isArray(data?.files) ? data.files : []; - const files: DeepScannedFileItem[] = rawFiles - .filter((f) => f && typeof f === "object") - .map((f) => ({ - fileId: String(f.fileId ?? f.id ?? ""), - id: Number(f.id ?? f.fileId ?? 0) || 0, - name: String(f.name || ""), - path: String(f.path || "/"), - size: Math.max(0, Number(f.size ?? 0) || 0), - type: String(f.type || "other"), - recoverable: f.recoverable !== false, - integrity: String(f.integrity || "good"), - isDeleted: Boolean(f.isDeleted) - })); - const totalCount = - typeof data?.totalCount === "number" && Number.isFinite(data.totalCount) ? data.totalCount : files.length; - return { files, totalCount }; -} - -/** 6/12: EnumFiles(同步分页查询扫描数据库中的文件) */ -export async function enumScanFiles( - params: { - scanId: string; - pageIndex?: number; - pageSize?: number; - fileType?: string; - searchKeyword?: string; - }, - hostOverride?: DynamicBridge -): Promise> { - const payload = { - scanId: params.scanId, - pageIndex: typeof params.pageIndex === "number" && Number.isFinite(params.pageIndex) ? params.pageIndex : 0, - pageSize: typeof params.pageSize === "number" && Number.isFinite(params.pageSize) ? params.pageSize : 100, - fileType: params.fileType || "all", - searchKeyword: params.searchKeyword || "" - }; - const res = await callDataRecoveryDll("EnumFiles", payload, "enumFilesFailed", hostOverride, false); - if (!res.ok) return { ok: false, error: res.error, errorCode: res.errorCode }; - return { ok: true, data: parseDeepFileRows(res.data) }; -} - -/** 7/12: EnumFilesAsync(异步回调查询扫描数据库中的文件) */ -export async function enumScanFilesAsync( - params: { - taskId: string; - scanId: string; - pageIndex?: number; - pageSize?: number; - fileType?: string; - searchKeyword?: string; - }, - hostOverride?: DynamicBridge -): Promise> { - const payload = { - taskId: params.taskId, - scanId: params.scanId, - pageIndex: typeof params.pageIndex === "number" && Number.isFinite(params.pageIndex) ? params.pageIndex : 0, - pageSize: typeof params.pageSize === "number" && Number.isFinite(params.pageSize) ? params.pageSize : 100, - fileType: params.fileType || "all", - searchKeyword: params.searchKeyword || "" - }; - return callDataRecoveryDll("EnumFilesAsync", payload, "enumFilesFailed", hostOverride, true); -} - -/** - * 8/12: RecoverFile(将扫描结果中的指定文件恢复到目标目录) - * 硬约束:调用 DLL 前必须通过 `validateRecoveryOutputTarget` 校验目标目录盘符严禁落在源待恢复分区! - */ -export async function recoverDeepFiles( - params: { - taskId: string; - scanId: string; - fileIds: string[]; - targetPath: string; - sourceDrives: string | string[]; - options?: { skipExisting?: boolean; overwriteExisting?: boolean }; - }, - hostOverride?: DynamicBridge -): Promise> { - const validation = validateRecoveryOutputTarget(params.sourceDrives, params.targetPath); - if (!validation.ok) { - return { - ok: false, - error: validation.error || getForbiddenReason(), - errorCode: validation.errorCode - }; - } - if (!Array.isArray(params.fileIds) || params.fileIds.length === 0) { - return { ok: false, error: t("selectFilesFirst"), errorCode: "EMPTY_SELECTION" }; - } - - const payload = { - taskId: params.taskId, - scanId: params.scanId, - fileIds: params.fileIds, - targetPath: params.targetPath, - options: params.options || { skipExisting: false, overwriteExisting: false } - }; - const res = await callDataRecoveryDll("RecoverFile", payload, "recoverFailed", hostOverride, true); - if (!res.ok) return { ok: false, error: res.error, errorCode: res.errorCode }; - return { - ok: true, - data: { - message: String(res.data?.message || "Recovery started"), - targetPath: params.targetPath - } - }; -} - -/** 9/12: GetFileMetadata(获取指定扫描文件的元数据详情) */ -export async function getDeepFileMetadata( - scanId: string, - fileId: string, - hostOverride?: DynamicBridge -): Promise> { - const res = await callDataRecoveryDll( - "GetFileMetadata", - { scanId, fileId }, - "metadataFailed", - hostOverride, - false - ); - if (!res.ok) return { ok: false, error: res.error, errorCode: res.errorCode }; - const d = res.data || {}; - return { - ok: true, - data: { - fileId, - id: Number(fileId) || 0, - name: String(d.name || ""), - path: String(d.path || "/"), - size: Math.max(0, Number(d.size ?? 0) || 0), - type: String(d.type || "other"), - recoverable: d.recoverable !== false, - integrity: String(d.integrity || "good"), - isDeleted: Boolean(d.isDeleted) - } - }; -} - -/** 10/12: PreviewFile(提取图片类扫描文件的临时预览路径) */ -export async function previewDeepFile( - scanId: string, - fileId: string, - hostOverride?: DynamicBridge -): Promise> { - const res = await callDataRecoveryDll( - "PreviewFile", - { scanId, fileId }, - "previewFailed", - hostOverride, - false - ); - if (!res.ok) return { ok: false, error: res.error, errorCode: res.errorCode }; - return { - ok: true, - data: { - previewPath: String(res.data?.previewPath || ""), - fileType: String(res.data?.fileType || "") - } - }; -} - -/** 11/12: GetScanStatus(查询指定扫描任务运行状态) */ -export async function getScanStatus( - taskId: string, - hostOverride?: DynamicBridge -): Promise> { - const res = await callDataRecoveryDll("GetScanStatus", { taskId }, "scanStatusFailed", hostOverride, false); - if (!res.ok) return { ok: false, error: res.error, errorCode: res.errorCode }; - const d = res.data || {}; - return { - ok: true, - data: { - scanning: Boolean(d.scanning), - ...(typeof d.scanId === "string" ? { scanId: d.scanId } : {}), - ...(typeof d.deviceId === "string" ? { deviceId: d.deviceId } : {}), - ...(typeof d.scanType === "string" ? { scanType: d.scanType } : {}) - } - }; -} - -/** 12/12: GetScanHistory(读取历史深度扫描记录) */ -export async function getScanHistory( - limit = 100, - hostOverride?: DynamicBridge -): Promise> { - const res = await callDataRecoveryDll( - "GetScanHistory", - { limit }, - "scanHistoryFailed", - hostOverride, - false - ); - if (!res.ok) return { ok: false, error: res.error, errorCode: res.errorCode }; - const rawList: DynamicBridge[] = Array.isArray(res.data?.history) ? res.data.history : []; - const history: DeepScanHistoryItem[] = rawList - .filter((h) => h && typeof h === "object") - .map((h) => ({ - scanId: String(h.scanId || ""), - deviceId: String(h.deviceId || ""), - deviceName: String(h.deviceName || h.deviceId || ""), - partitionNum: typeof h.partitionNum === "number" && Number.isFinite(h.partitionNum) ? h.partitionNum : -1, - scanType: String(h.scanType || "quick"), - scanScenario: String(h.scanScenario || "deleted"), - startTime: Number(h.startTime ?? 0) || 0, - endTime: typeof h.endTime === "number" && Number.isFinite(h.endTime) ? h.endTime : null, - totalFiles: Math.max(0, Number(h.totalFiles ?? 0) || 0), - totalSize: Math.max(0, Number(h.totalSize ?? 0) || 0), - status: String(h.status || ""), - description: String(h.description || ""), - cacheAvailable: Boolean(h.cacheAvailable) - })); - return { ok: true, data: history }; -} - -export async function showRecoveryItem(targetPath: string, hostBridge?: DynamicBridge): Promise { - if (!targetPath) return false; - return showRealItemInFolder(targetPath, hostBridge); -} - -export async function openRecoveryFolder(dirPath: string, hostBridge?: DynamicBridge): Promise { - if (!dirPath) return false; - return openRealPath(dirPath, hostBridge); -} - -export { formatModified }; diff --git a/extensions/data-recovery/src/native-ipc.ts b/extensions/data-recovery/src/native-ipc.ts deleted file mode 100644 index 1364327..0000000 --- a/extensions/data-recovery/src/native-ipc.ts +++ /dev/null @@ -1,1902 +0,0 @@ -import { getLocale } from '@ztools/declarative-ui' - -type DynamicBridge = ReturnType - -const NATIVE_IPC_MESSAGES: Record string - dirEntrySep: string - dirErrorColon: string - deepScanUnavailable: string - pathEmpty: string - invalidMethodEmpty: string - invalidMethodFormat: string - invalidParamsObject: string - paramTooLong: (key: string) => string - paramOutOfRange: (key: string) => string - methodParamEmpty: string - invalidMethodType: string - malformedDllResponse: string - unknownDllError: string - hostIpcFailed: (pluginName: string, method: string) => string - hostUnavailable: (pluginName: string, method: string) => string - callFailed: string - movedToTrash: string - deleteFailed: string - revealedInFolder: string - revealFailed: string - opened: string - openFailed: string - pluginCallNotReady: string -}> = { - 'zh-CN': { - ipcCallFailed: 'IPC 调用返回失败', - ipcInnerFailed: 'IPC 内部调用失败', - scanIncomplete: '扫描结果不完整', - dirReadFailed: (details, moreCount) => - `目录读取失败或不完整:${details}${moreCount > 0 ? `;另有 ${moreCount} 个目录` : ''}`, - dirEntrySep: ';', - dirErrorColon: ':', - deepScanUnavailable: '深度扫描不可用,仅列出一级目录,结果不完整', - pathEmpty: '路径不能为空', - invalidMethodEmpty: 'INVALID_METHOD: 调用方法名不能为空', - invalidMethodFormat: 'INVALID_METHOD_FORMAT: 方法名包含非法字符或超长', - invalidParamsObject: 'INVALID_PARAMS: 参数必须为非空对象', - paramTooLong: (key) => `PARAM_TOO_LONG: 参数 ${key} 超过最大长度限制`, - paramOutOfRange: (key) => `PARAM_OUT_OF_RANGE: 数值参数 ${key} 越界或非有限数`, - methodParamEmpty: 'method 参数不能为空', - invalidMethodType: 'INVALID_METHOD: method 不能为空且必须为字符串', - malformedDllResponse: 'MALFORMED_DLL_RESPONSE: 原生组件返回了损坏的 JSON 数据', - unknownDllError: '原生组件返回未知错误', - hostIpcFailed: (pluginName, method) => `HOST_IPC_FAILED: ${pluginName}.${method} 调用失败`, - hostUnavailable: (pluginName, method) => `HOST_UNAVAILABLE: ${pluginName}.${method} 宿主接口未就绪`, - callFailed: '调用失败', - movedToTrash: '已移入回收站', - deleteFailed: '删除失败', - revealedInFolder: '已定位文件', - revealFailed: '定位失败', - opened: '已打开', - openFailed: '打开失败', - pluginCallNotReady: '插件调用未就绪' - }, - 'en-US': { - ipcCallFailed: 'IPC call failed', - ipcInnerFailed: 'Internal IPC call failed', - scanIncomplete: 'Incomplete scan results', - dirReadFailed: (details, moreCount) => - `Directory read failed or incomplete: ${details}${moreCount > 0 ? `; and ${moreCount} more` : ''}`, - dirEntrySep: '; ', - dirErrorColon: ': ', - deepScanUnavailable: 'Deep scan unavailable; only top-level directory listed (incomplete)', - pathEmpty: 'Path cannot be empty', - invalidMethodEmpty: 'INVALID_METHOD: Method name cannot be empty', - invalidMethodFormat: 'INVALID_METHOD_FORMAT: Method name contains invalid characters or is too long', - invalidParamsObject: 'INVALID_PARAMS: Parameters must be a non-null object', - paramTooLong: (key) => `PARAM_TOO_LONG: Parameter "${key}" exceeds maximum length`, - paramOutOfRange: (key) => `PARAM_OUT_OF_RANGE: Numeric parameter "${key}" is out of range or non-finite`, - methodParamEmpty: 'Method parameter cannot be empty', - invalidMethodType: 'INVALID_METHOD: Method must be a non-empty string', - malformedDllResponse: 'MALFORMED_DLL_RESPONSE: Native component returned malformed JSON', - unknownDllError: 'Native component returned an unknown error', - hostIpcFailed: (pluginName, method) => `HOST_IPC_FAILED: ${pluginName}.${method} call failed`, - hostUnavailable: (pluginName, method) => `HOST_UNAVAILABLE: ${pluginName}.${method} host interface not ready`, - callFailed: 'Call failed', - movedToTrash: 'Moved to Trash', - deleteFailed: 'Delete failed', - revealedInFolder: 'Revealed in folder', - revealFailed: 'Failed to reveal item', - opened: 'Opened', - openFailed: 'Failed to open', - pluginCallNotReady: 'Plugin invocation not ready' - } -} - -function ipcStrings() { - const locale = getLocale() - return NATIVE_IPC_MESSAGES[locale] ?? NATIVE_IPC_MESSAGES['en-US'] -} -/** - * ZTools 真实宿主 IPC 与系统能力桥接层 (Real Host IPC Bridge) - * - * 严格遵循《ZTools Declarative UI 2.0 架构与 35 款原生插件全量升级规范》5.1 真实环境铁律: - * - 在真实 Electron 宿主环境中,100% 走通 Preload (__ztoolsElectron.transport.methods / window.ztools / __ztoolsLauncher) 真实调用链路 - * - 严禁在真实环境中因参数格式或嵌套响应结构差异而回退到假数据 - */ - -let ipcReqSeq = 1 -const realFileSizeCache = new Map() - -export function nextMessageId(prefix = 'ipc'): string { - ipcReqSeq = (ipcReqSeq + 1) % 1_000_000 - return `${prefix}_${Date.now()}_${ipcReqSeq}` -} - -/** - * 判断当前是否处于真实的 ZTools Electron 渲染进程宿主环境 - */ -export function isRealElectronHost(hostOverride?: unknown): boolean { - if (hostOverride) return false - if (typeof window === 'undefined') return false - const w = window as DynamicBridge - return Boolean( - w.__ztoolsElectron?.transport?.methods || - w.ztools?.transport?.call || - w.ztools?.transport?.methods - ) -} - -function normalizeMethodParams(method: string, params: Record): Record { - if (!params || typeof params !== 'object') return {} - const next = { ...params } - if (method === 'system_get_disk_usage') { - const rawDrive = String(next.drive || next.path || 'C:\\').trim() - if (rawDrive.startsWith('/')) { - next.drive = rawDrive - } else { - const match = rawDrive.match(/^([A-Za-z]):/) - next.drive = match ? `${match[1].toUpperCase()}:\\` : rawDrive.replace(/\//g, '\\') - } - delete next.path - } - return next -} - -function normalizeMethodResult(method: string, payload: DynamicBridge): DynamicBridge { - if (!payload || typeof payload !== 'object') return payload - - if (method === 'system_get_disk_usage') { - const avail = typeof payload.available === 'number' - ? payload.available - : typeof payload.free === 'number' - ? payload.free - : Math.max(0, Number(payload.total || 0) - Number(payload.used || 0)) - return { - ...payload, - available: avail, - free: avail - } - } - - if (method === 'system_get_hardware_summary') { - const cpuModel = - typeof payload.cpuModel === 'string' && payload.cpuModel.trim() - ? payload.cpuModel.trim() - : Array.isArray(payload.cpuModels) && payload.cpuModels.length > 0 - ? String(payload.cpuModels[0]).trim() - : 'x86_64 Processor' - return { - ...payload, - cpuModel - } - } - - if (method === 'system_get_battery_status') { - // 宿主约定 percent 超出 0-100(如 255)表示无电池或电量未知,不能改写成 100% - // 若宿主明确给出 hasBattery 布尔值,必须原样保留,仅在缺失时按合法电量推算 - const rawPct = payload.percent - const validPct = typeof rawPct === 'number' && Number.isFinite(rawPct) && rawPct >= 0 && rawPct <= 100 - const hasBattery = typeof payload.hasBattery === 'boolean' ? payload.hasBattery : validPct - return { - ...payload, - percent: validPct ? rawPct : null, - hasBattery - } - } - - if (method === 'screen_get_all_displays') { - const list = Array.isArray(payload) - ? payload - : Array.isArray(payload.displays) - ? payload.displays - : [] - return list.map((d: DynamicBridge) => ({ - ...d, - label: d?.label || d?.name || `Display #${d?.id ?? 1}` - })) - } - - return payload -} - -function extractIpcErrorMeta(errObj: DynamicBridge): { - errorCode?: string - errorDetails?: Record -} { - if (!errObj || typeof errObj !== 'object') return {} - const errorCode = - typeof errObj.errorCode === 'string' && errObj.errorCode.trim() - ? errObj.errorCode.trim() - : typeof errObj.code === 'string' && errObj.code.trim() - ? errObj.code.trim() - : undefined - const rawDetails = - errObj.errorDetails && typeof errObj.errorDetails === 'object' && !Array.isArray(errObj.errorDetails) - ? (errObj.errorDetails as Record) - : errObj.details && typeof errObj.details === 'object' && !Array.isArray(errObj.details) - ? (errObj.details as Record) - : undefined - return { - ...(errorCode ? { errorCode } : {}), - ...(rawDetails ? { errorDetails: rawDetails } : {}) - } -} - -function unwrapTransportResponse( - method: string, - raw: DynamicBridge -): { ok: boolean; data?: DynamicBridge; error?: string; errorCode?: string; errorDetails?: Record } { - if (raw === null || raw === undefined) { - return { ok: false, error: 'EMPTY_IPC_RESPONSE', errorCode: 'EMPTY_IPC_RESPONSE' } - } - if (typeof raw !== 'object') { - return { ok: true, data: raw } - } - if (raw.success === false) { - const errObj = raw.error - const errMsg = - typeof errObj === 'object' && errObj !== null - ? String(errObj.message || errObj.code || JSON.stringify(errObj)) - : String(errObj || ipcStrings().ipcCallFailed) - return { ok: false, error: errMsg, ...extractIpcErrorMeta(raw), ...extractIpcErrorMeta(errObj) } - } - - const firstLayer = 'data' in raw && raw.data !== undefined ? raw.data : raw - if (firstLayer && typeof firstLayer === 'object' && !Array.isArray(firstLayer)) { - if (firstLayer.success === false) { - const errObj = firstLayer.error - const errMsg = - typeof errObj === 'object' && errObj !== null - ? String(errObj.message || errObj.code || JSON.stringify(errObj)) - : String(errObj || ipcStrings().ipcInnerFailed) - return { ok: false, error: errMsg, ...extractIpcErrorMeta(firstLayer), ...extractIpcErrorMeta(errObj) } - } - if ('data' in firstLayer && firstLayer.data !== undefined) { - return { ok: true, data: normalizeMethodResult(method, firstLayer.data) } - } - } - - return { ok: true, data: normalizeMethodResult(method, firstLayer) } -} - -/** - * 调用 Electron Preload Transport 方法(自动封装合法的 alphanumeric messageId 与双层解包) - */ -export async function callHostTransport( - method: string, - params: Record = {}, - hostOverride?: DynamicBridge -): Promise<{ ok: boolean; data?: T; error?: string; errorCode?: string; errorDetails?: Record }> { - const normalizedParams = normalizeMethodParams(method, params) - - // 1. 测试注入的 hostOverride 优先 - if (hostOverride) { - if (typeof hostOverride[method] === 'function') { - try { - const res = await hostOverride[method](normalizedParams) - const unwrapped = unwrapTransportResponse(method, res) - return unwrapped as { ok: boolean; data?: T; error?: string; errorCode?: string; errorDetails?: Record } - } catch (err: DynamicBridge) { - return { ok: false, error: err instanceof Error ? err.message : String(err), ...extractIpcErrorMeta(err) } - } - } - if (typeof hostOverride?.transport?.call === 'function') { - try { - const res = await hostOverride.transport.call(method, normalizedParams) - const unwrapped = unwrapTransportResponse(method, res) - return unwrapped as { ok: boolean; data?: T; error?: string; errorCode?: string; errorDetails?: Record } - } catch (err: DynamicBridge) { - return { ok: false, error: err instanceof Error ? err.message : String(err), ...extractIpcErrorMeta(err) } - } - } - } - - if (typeof window === 'undefined') { - return { ok: false, error: 'NO_WINDOW_ENV', errorCode: 'NO_WINDOW_ENV' } - } - - const w = window as DynamicBridge - const methods = w.__ztoolsElectron?.transport?.methods || w.ztools?.transport?.methods - const fn = methods?.[method] - - if (typeof fn === 'function') { - try { - const messageId = nextMessageId(method.replace(/[^A-Za-z0-9_]/g, '_').slice(0, 24)) - const raw = await fn({ messageId, params: normalizedParams }) - return unwrapTransportResponse(method, raw) as { ok: boolean; data?: T; error?: string; errorCode?: string; errorDetails?: Record } - } catch (err: DynamicBridge) { - return { ok: false, error: err instanceof Error ? err.message : String(err), ...extractIpcErrorMeta(err) } - } - } - - if (typeof w.ztools?.transport?.call === 'function') { - try { - const raw = await w.ztools.transport.call(method, normalizedParams) - return unwrapTransportResponse(method, raw) as { ok: boolean; data?: T; error?: string; errorCode?: string; errorDetails?: Record } - } catch (err: DynamicBridge) { - return { ok: false, error: err instanceof Error ? err.message : String(err), ...extractIpcErrorMeta(err) } - } - } - - return { ok: false, error: `METHOD_NOT_AVAILABLE: ${method}`, errorCode: 'METHOD_NOT_AVAILABLE' } -} - -export interface RealDiskDriveInfo { - drive: string - totalBytes: number - usedBytes: number - availableBytes: number - usagePercent: number -} - -/** - * 探测本机全部真实挂载磁盘分区 (C:\ ~ Z:\ 或 macOS/POSIX 挂载点 '/') - */ -export async function probeRealDiskDrives( - candidateLetters: string[] = ['C', 'D', 'E', 'F', 'G'], - hostOverride?: DynamicBridge -): Promise { - const drives: RealDiskDriveInfo[] = [] - const results = await Promise.all( - candidateLetters.map(async (letter) => { - const raw = String(letter || '').trim() - const isPosix = raw.startsWith('/') - const drivePath = isPosix ? raw : `${raw.replace(/:\\?$/, '').toUpperCase()}:\\` - const res = await callHostTransport<{ - total: number - used: number - available: number - free?: number - percent: number - }>('system_get_disk_usage', { drive: drivePath }, hostOverride) - if (res.ok && res.data && typeof res.data.total === 'number' && res.data.total > 0) { - const availableBytes = - typeof res.data.available === 'number' - ? res.data.available - : typeof res.data.free === 'number' - ? res.data.free - : Math.max(0, res.data.total - res.data.used) - return { - drive: isPosix ? raw : `${raw.replace(/:\\?$/, '').toUpperCase()}:`, - totalBytes: res.data.total, - usedBytes: res.data.used, - availableBytes, - usagePercent: res.data.percent - } - } - return null - }) - ) - - for (const item of results) { - if (item) drives.push(item) - } - - if (drives.length === 0 && !candidateLetters.includes('/')) { - const posixRes = await callHostTransport<{ - total: number - used: number - available: number - free?: number - percent: number - }>('system_get_disk_usage', { drive: '/' }, hostOverride) - if (posixRes.ok && posixRes.data && typeof posixRes.data.total === 'number' && posixRes.data.total > 0) { - const availableBytes = - typeof posixRes.data.available === 'number' - ? posixRes.data.available - : typeof posixRes.data.free === 'number' - ? posixRes.data.free - : Math.max(0, posixRes.data.total - posixRes.data.used) - drives.push({ - drive: '/', - totalBytes: posixRes.data.total, - usedBytes: posixRes.data.used, - availableBytes, - usagePercent: posixRes.data.percent - }) - } - } - - return drives -} - -/** - * 获取本机真实系统特殊路径(支持 home 派生标准子目录兜底,自动兼容 Windows 与 macOS/POSIX) - */ -export async function getRealSystemPath( - name: 'home' | 'appData' | 'userData' | 'desktop' | 'documents' | 'downloads' | 'music' | 'pictures' | 'videos' | 'temp' | 'cache', - hostOverride?: DynamicBridge -): Promise { - const res = await callHostTransport('system_get_path', { name }, hostOverride) - if (res.ok && res.data) { - if (typeof res.data === 'string' && res.data.trim().length > 0) { - return res.data.trim() - } - if (typeof res.data.path === 'string' && res.data.path.trim().length > 0) { - return res.data.path.trim() - } - } - - if (name !== 'home') { - const home = await getRealSystemPath('home', hostOverride) - if (home) { - const isPosix = home.startsWith('/') - const subMap: Record = isPosix - ? { - desktop: `${home}/Desktop`, - documents: `${home}/Documents`, - downloads: `${home}/Downloads`, - music: `${home}/Music`, - pictures: `${home}/Pictures`, - videos: `${home}/Videos`, - appData: `${home}/Library/Application Support`, - userData: `${home}/Library/Application Support/ZTools`, - temp: '/tmp', - cache: `${home}/Library/Caches` - } - : { - desktop: `${home}\\Desktop`, - documents: `${home}\\Documents`, - downloads: `${home}\\Downloads`, - music: `${home}\\Music`, - pictures: `${home}\\Pictures`, - videos: `${home}\\Videos`, - appData: `${home}\\AppData\\Roaming`, - userData: `${home}\\AppData\\Roaming\\ZTools`, - temp: `${home}\\AppData\\Local\\Temp`, - cache: `${home}\\AppData\\Local` - } - if (subMap[name]) return subMap[name] - } - } - - return '' -} - -export type RealDriveUsageInfo = RealDiskDriveInfo - -export interface RealIndexedFileEntry { - name: string - path: string - ext: string - isDir: boolean - isDirectory: boolean - size: number - sizeBytes: number - mtime: number - mtimeMs: number - lastModifiedMs: number -} - -export interface RealDirectorySubdirSummary { - name: string - path: string - fileCount: number - totalBytes: number - mtime: number - /** 体积不是完整统计(宿主扫描截断且独立统计超时 / 无权限),totalBytes 只是下限 */ - approximate?: boolean -} - -export interface RealDirectoryScanResult extends Iterable { - files: RealIndexedFileEntry[] - totalFiles: number - fileCount: number - totalBytes: number - subdirs: RealDirectorySubdirSummary[] - /** 宿主扫描达到条目上限后停止:files / totalFiles 只是已遍历部分的抽样 */ - truncated?: boolean - /** totalBytes 为近似值(下限) */ - approximate?: boolean - /** 宿主实际遍历的条目数 */ - visitedEntries?: number - /** 目录本身不存在(ENOENT) */ - missing?: boolean - /** 读取失败的真实原因;已有文件仍可使用,但不能当作完整结果。 */ - error?: string -} - -interface ScanResultMeta { - truncated?: boolean - approximate?: boolean - visitedEntries?: number - missing?: boolean -} - -export interface ScanDirectoryTreeOptions { - maxDepth?: number - maxFiles?: number - collectTopN?: number - filterExt?: RegExp - /** 为 true 时,目录本身不存在(ENOENT)按空目录处理,不返回 error(权限拒绝/读取失败仍照常报错) */ - ignoreMissing?: boolean - /** Top-N 保留与排序方式:默认按体积降序,下载/录屏等时效场景可传 mtime-desc */ - sortBy?: 'size-desc' | 'mtime-desc' - hostOverride?: DynamicBridge -} - -function extractFileExt(fileNameOrPath: string): string { - const base = String(fileNameOrPath || '').split(/[\\/]/).pop() || '' - const dotIdx = base.lastIndexOf('.') - return dotIdx > 0 ? base.slice(dotIdx).toLowerCase() : '' -} - -function normalizeIndexedFileEntry(f: DynamicBridge): RealIndexedFileEntry { - const p = String(f?.path || '') - const name = String(f?.name || p.split(/[\\/]/).pop() || '') - const sz = Number(f?.size ?? f?.sizeBytes ?? 0) - const isDir = Boolean(f?.is_dir || f?.isDir || f?.isDirectory) - const rawMtime = Number(f?.mtime ?? f?.mtimeMs ?? 0) - const validMtime = Number.isFinite(rawMtime) && rawMtime > 0 - const mtimeMs = validMtime ? (rawMtime > 1e11 ? rawMtime : rawMtime * 1000) : 0 - const mtimeSec = validMtime ? (rawMtime > 1e11 ? Math.floor(rawMtime / 1000) : rawMtime) : 0 - if (p && sz >= 0) realFileSizeCache.set(p, sz) - return { - name, - path: p, - ext: extractFileExt(name || p), - isDir, - isDirectory: isDir, - size: sz, - sizeBytes: sz, - mtime: mtimeSec, - mtimeMs, - lastModifiedMs: mtimeMs - } -} - -function makeScanResult( - files: RealIndexedFileEntry[], - totalFiles: number, - totalBytes: number, - subdirs: RealDirectorySubdirSummary[], - meta: ScanResultMeta = {} -): RealDirectoryScanResult { - return { - files, - totalFiles, - fileCount: totalFiles, - totalBytes, - subdirs, - ...(meta.truncated ? { truncated: true } : {}), - ...(meta.approximate ? { approximate: true } : {}), - ...(meta.missing ? { missing: true } : {}), - ...(typeof meta.visitedEntries === 'number' ? { visitedEntries: meta.visitedEntries } : {}), - [Symbol.iterator]() { - return files[Symbol.iterator]() - } - } -} - -/** - * 调用客户端的原生文件索引组件 (ztools-indexer) 检索文件 - */ -export async function searchRealIndexedFiles( - query: string, - limit = 40, - hostOverride?: DynamicBridge -): Promise { - if (!query || !query.trim()) return [] - const q = query.trim() - const safeLimit = Math.min(200, Math.max(1, Math.floor(limit || 40))) - - try { - const res = await callHostTransport<{ files?: DynamicBridge[] }>( - 'system_search_files', - { query: q, limit: safeLimit }, - hostOverride - ) - if (res.ok && res.data && Array.isArray(res.data.files)) { - return res.data.files.map(normalizeIndexedFileEntry) - } - - if (!hostOverride && typeof window !== 'undefined') { - const w = window as DynamicBridge - if (typeof w.__ztoolsLauncher?.searchFiles === 'function') { - const rawOuter = await w.__ztoolsLauncher.searchFiles(q, safeLimit) - const raw = rawOuter && typeof rawOuter === 'object' && 'data' in rawOuter && rawOuter.data ? rawOuter.data : rawOuter - if (raw && Array.isArray(raw.files)) { - return raw.files.map(normalizeIndexedFileEntry) - } - } - } - } catch { - // ignore - } - return [] -} - -/** - * 深度扫描指定真实物理目录树(支持符号链接穿透,如 AppData\Roaming\Tencent -> D:\Local\Roaming\Tencent) - * 返回该目录下 Top 文件列表、全树真实文件总数、全树真实总字节数与一级子目录汇总 - */ -export async function scanRealDirectoryTree( - dirPath: string, - limitOrOptions: number | ScanDirectoryTreeOptions = 160, - hostOverrideArg?: DynamicBridge -): Promise { - const result = await scanDirectoryTreeWithError(dirPath, limitOrOptions, hostOverrideArg) - return result.error ? { ...result.scan, error: result.error } : result.scan -} - -/** 仅当正则明确声明了扩展名(含 `\.`)时提取后缀列表,避免把 `thumbcache|iconcache` 等文件名关键词误拆成假扩展名 */ -function extractExtensionTokensFromFilter(filterExt: RegExp): string[] { - const src = filterExt.source - if (!src.includes('\\.')) return [] - const afterDot = src.slice(src.indexOf('\\.') + 2) - const rawTokens = afterDot.match(/[a-z0-9]{1,8}/gi) || [] - const seen = new Set() - const out: string[] = [] - for (const token of rawTokens) { - const lower = token.toLowerCase() - if (!lower || seen.has(lower)) continue - seen.add(lower) - out.push(lower) - } - return out -} - -function isMissingDirectoryError(res: { error?: string; errorCode?: string; errorDetails?: Record }): boolean { - if (res.errorDetails?.reason === 'ENOENT' || res.errorCode === 'ENOENT') return true - const msg = String(res.error || '') - return /Directory does not exist|ENOENT/i.test(msg) -} - -/** 一次界面扫描的错误汇总;多个目录并行扫描时保留可读目录的结果。 */ -export function createDirectoryScanner(hostOverride?: DynamicBridge) { - const failures = new Map() - return { - async scan(dir: string, options: number | ScanDirectoryTreeOptions = 160) { - const result = await scanRealDirectoryTree(dir, options, hostOverride) - const ignoreMissing = typeof options === 'object' && options !== null && options.ignoreMissing === true - const error = - result.missing && ignoreMissing - ? '' - : result.error || (result.truncated || result.approximate ? ipcStrings().scanIncomplete : '') - if (error) failures.set(dir, error) - else failures.delete(dir) - return result - }, - get error(): string | undefined { - if (!failures.size) return undefined - const s = ipcStrings() - const details = [...failures].slice(0, 3).map(([dir, error]) => `${dir}${s.dirErrorColon}${error}`).join(s.dirEntrySep) - return s.dirReadFailed(details, Math.max(0, failures.size - 3)) - } - } -} - -/** scanRealDirectoryTree 的实现:额外带回读取失败原因(目录不存在 / 为空 / 无权限 / 载荷异常) */ -async function scanDirectoryTreeWithError( - dirPath: string, - limitOrOptions: number | ScanDirectoryTreeOptions, - hostOverrideArg?: DynamicBridge -): Promise<{ scan: RealDirectoryScanResult; error?: string }> { - const empty = makeScanResult([], 0, 0, []) - if (!dirPath || !dirPath.trim()) return { scan: empty, error: 'EMPTY_DIRECTORY_PATH' } - const targetDir = dirPath.trim() - - const opts: ScanDirectoryTreeOptions = - typeof limitOrOptions === 'number' - ? { maxFiles: limitOrOptions, hostOverride: hostOverrideArg } - : { ...limitOrOptions, hostOverride: limitOrOptions?.hostOverride ?? hostOverrideArg } - - const rawLimit = opts.maxFiles ?? opts.collectTopN ?? 160 - const safeLimit = Math.min(200, Math.max(1, Math.floor(rawLimit || 160))) - const hostOverride = opts.hostOverride - const filterExt = opts.filterExt - const ignoreMissing = opts.ignoreMissing === true - const dirQuery = `dir:${targetDir}` - - try { - let rawPayload: DynamicBridge = null - const searchParams: Record = { - query: dirQuery, - limit: safeLimit, - ...(opts.sortBy ? { sortBy: opts.sortBy } : {}) - } - const res = await callHostTransport( - 'system_search_files', - searchParams, - hostOverride - ) - if (res.ok && res.data && res.data.degraded !== true) { - rawPayload = res.data - } else if (!res.ok && ignoreMissing && isMissingDirectoryError(res)) { - const missingScan = makeScanResult([], 0, 0, [], { missing: true }) - return { scan: missingScan } - } - if (!rawPayload && !hostOverride && res.errorCode === 'METHOD_NOT_AVAILABLE' && typeof window !== 'undefined') { - const w = window as DynamicBridge - if (typeof w.__ztoolsLauncher?.searchFiles === 'function') { - const rawOuter = await w.__ztoolsLauncher.searchFiles(dirQuery, safeLimit) - const candidate = - rawOuter && typeof rawOuter === 'object' && 'data' in rawOuter && rawOuter.data - ? rawOuter.data - : rawOuter - if (candidate && candidate.degraded !== true && candidate.success !== false) { - rawPayload = candidate - } - } - } - - if ( - rawPayload && - Array.isArray(rawPayload.files) - ) { - let files: RealIndexedFileEntry[] = rawPayload.files.map(normalizeIndexedFileEntry) - if (filterExt instanceof RegExp) { - files = files.filter(f => !f.isDir && (filterExt.test(f.name) || filterExt.test(f.ext))) - // 若目录 Top-N 大文件均为其他后缀,使用 MFT 索引直接检索明确声明的目标扩展名 - if (files.length === 0 && !hostOverride) { - const extTokens = extractExtensionTokensFromFilter(filterExt) - if (extTokens.length > 0) { - // 只接受确实位于目标目录下的检索结果,不能用别处同后缀文件冒充目录内容 - const prefixLower = `${targetDir.replace(/[\\/]+$/, '')}${isWindowsStylePath(targetDir) ? '\\' : '/'}`.toLowerCase() - const extraLists = await Promise.all( - extTokens.map(ext => searchRealIndexedFiles(`.${ext}`, 30, hostOverride)) - ) - const seen = new Set() - for (const list of extraLists) { - for (const item of list) { - if (!item.isDir && item.size > 0 && !seen.has(item.path)) { - if (item.path.replace(/\//g, isWindowsStylePath(targetDir) ? '\\' : '/').toLowerCase().startsWith(prefixLower)) { - seen.add(item.path) - files.push(item) - } - } - } - } - } - } - } - // 先基于过滤后的完整命中集合计算总文件数与总字节数,再按 collectTopN 裁剪样本列表 - const matchedCount = files.length - const matchedBytes = files.reduce((acc, f) => acc + (f.isDir ? 0 : f.size), 0) - if (typeof opts.collectTopN === 'number' && opts.collectTopN > 0 && files.length > opts.collectTopN) { - files = files.slice(0, opts.collectTopN) - } - const subdirs: RealDirectorySubdirSummary[] = Array.isArray(rawPayload.subdirs) - ? rawPayload.subdirs.map((s: DynamicBridge) => ({ - name: String(s.name || ''), - path: String(s.path || ''), - fileCount: Number(s.file_count ?? s.fileCount ?? 0), - totalBytes: Number(s.total_bytes ?? s.totalBytes ?? 0), - mtime: Number(s.mtime || 0), - ...(s.approximate === true ? { approximate: true } : {}) - })) - : [] - const totalFilesCount = - filterExt instanceof RegExp ? matchedCount : Number(rawPayload.total_matches ?? matchedCount) - const totalBytesCount = - filterExt instanceof RegExp ? matchedBytes : Number(rawPayload.total_bytes ?? matchedBytes) - const visited = Number(rawPayload.visited_entries) - return { - scan: makeScanResult(files, totalFilesCount, totalBytesCount, subdirs, { - truncated: rawPayload.truncated === true, - approximate: rawPayload.approximate === true, - ...(Number.isFinite(visited) && visited >= 0 ? { visitedEntries: visited } : {}) - }), - ...(typeof rawPayload.scan_error === 'string' && rawPayload.scan_error ? { error: rawPayload.scan_error } : {}) - } - } - - // 深度扫描失败或回执无效时,仅以一级目录读取补回可见结果;不冒充完整目录树。 - const listing = await listDirectoryViaFilesystem(targetDir, hostOverride, { withSizes: true, limit: safeLimit }) - if (listing.ok && listing.entries.length > 0) { - const files: RealIndexedFileEntry[] = [] - let totalBytes = 0 - for (const entry of listing.entries) { - if (filterExt instanceof RegExp && !filterExt.test(entry.name) && !filterExt.test(entry.ext)) { - continue - } - files.push(entry) - totalBytes += entry.isDir ? 0 : entry.size - } - const incomplete = listing.entries.some(entry => entry.isDir) || listing.entries.length >= safeLimit - return { - scan: makeScanResult(files, files.filter(file => !file.isDir).length, totalBytes, [], { approximate: incomplete }), - ...(incomplete ? { error: res.error || ipcStrings().deepScanUnavailable } : {}) - } - } - return listing.ok ? { scan: empty } : { scan: empty, error: listing.error || 'DIRECTORY_READ_FAILED' } - } catch (error) { - return { scan: empty, error: error instanceof Error ? error.message : String(error) } - } -} - - -/** 目录读取不到任何条目(不存在 / 为空 / 无权限)时的错误码 */ -export const DIRECTORY_EMPTY_OR_UNREADABLE = 'DIRECTORY_EMPTY_OR_UNREADABLE' - -export interface RealDirectoryListingResult { - /** 目录内条目的完整路径;读取失败时为空数组 */ - entries: string[] - /** 读取失败或目录为空时的错误码 / 宿主错误信息 */ - error?: string -} - -export interface RealDirectChildrenResult { - /** 目录的直接子项(子目录在前),按路径去重 */ - entries: RealIndexedFileEntry[] - /** 宿主扫描达到条目上限,可能只返回了部分直接子项 */ - partial: boolean - error?: string -} - -function stripTrailingSeparators(p: string): string { - const trimmed = p.replace(/[\\/]+$/, '') - return trimmed || p.slice(0, 1) -} - -function isWindowsStylePath(p: string): boolean { - return /^[A-Za-z]:/.test(p) || p.startsWith('\\\\') || (p.includes('\\') && !p.includes('/')) -} - -function comparablePath(p: string): string { - const stripped = stripTrailingSeparators(String(p || '').trim()) - return isWindowsStylePath(stripped) ? stripped.replace(/\//g, '\\').toLowerCase() : stripped -} - -function parentDirOf(p: string): string { - const stripped = stripTrailingSeparators(String(p || '')) - const idx = Math.max(stripped.lastIndexOf('/'), stripped.lastIndexOf('\\')) - if (idx < 0) return '' - if (idx === 0) return stripped.slice(0, 1) - const parent = stripped.slice(0, idx) - return /^[A-Za-z]:$/.test(parent) ? `${parent}\\` : parent -} - -function isDirectChildPath(dirPath: string, candidate: string): boolean { - if (!candidate) return false - return comparablePath(parentDirOf(candidate)) === comparablePath(dirPath) -} - -function joinChildPath(dirPath: string, name: string): string { - const sep = isWindowsStylePath(dirPath) ? '\\' : '/' - const base = dirPath.replace(/[\\/]+$/, '') - return `${base}${sep}${name}` -} - -/** - * 通过 filesystem_get_directory_contents 读取一级目录(需宿主授权)。 - * 宿主真实返回 { success, files: [{ name, size, isDirectory, lastModified }] }(name 为文件名); - * 兼容旧测试替身返回的完整路径字符串数组。 - */ -async function listDirectoryViaFilesystem( - dirPath: string, - hostOverride: DynamicBridge, - options: { withSizes?: boolean; limit?: number } = {} -): Promise<{ ok: boolean; entries: RealIndexedFileEntry[]; error?: string }> { - const res = await callHostTransport('filesystem_get_directory_contents', { path: dirPath }, hostOverride) - if (!res.ok) return { ok: false, entries: [], error: res.error || 'DIRECTORY_READ_FAILED' } - const data = res.data - const rawList: unknown[] | null = Array.isArray(data) ? data : Array.isArray(data?.files) ? data.files : null - if (!rawList) return { ok: false, entries: [], error: 'INVALID_DIRECTORY_PAYLOAD' } - - const limit = Math.max(1, Math.floor(options.limit ?? 1000)) - const nowSec = Math.floor(Date.now() / 1000) - const entries: RealIndexedFileEntry[] = [] - const seen = new Set() - for (const item of rawList) { - if (entries.length >= limit) break - let entry: RealIndexedFileEntry | null = null - if (typeof item === 'string') { - const itemPath = item.trim() - if (!itemPath) continue - const name = itemPath.split(/[\\/]/).pop() || itemPath - const sz = options.withSizes ? await getRealFileSize(itemPath, hostOverride) : 0 - entry = normalizeIndexedFileEntry({ - name, - path: itemPath, - isDir: sz === 0 && !name.includes('.'), - size: sz, - mtime: nowSec - }) - } else if (item && typeof item === 'object' && typeof (item as DynamicBridge).name === 'string') { - const raw = item as DynamicBridge - const rawName = raw.name.trim() - if (!rawName || rawName === '.' || rawName === '..') continue - // 只接受文件名,或确实位于该目录下的完整路径,拒绝越界路径 - const fullPath = /[\\/]/.test(rawName) ? rawName : joinChildPath(dirPath, rawName) - if (!isDirectChildPath(dirPath, fullPath)) continue - const isDir = Boolean(raw.isDirectory ?? raw.isDir ?? raw.is_dir) - const parsedMtime = Date.parse(String(raw.lastModified || '')) - entry = normalizeIndexedFileEntry({ - name: fullPath.split(/[\\/]/).pop() || rawName, - path: fullPath, - isDir, - size: isDir ? 0 : Math.max(0, Number(raw.size) || 0), - mtime: Number.isFinite(parsedMtime) ? parsedMtime : nowSec - }) - } - if (!entry || seen.has(entry.path)) continue - seen.add(entry.path) - entries.push(entry) - } - return { ok: true, entries } -} - -/** - * 读取真实目录下的条目路径(真实宿主中优先走 dir: 扫描:一级子目录 + 全树 Top-N 大文件),并返回失败原因。 - * 目录不存在、为空或无权限时返回空列表与错误码,绝不用全盘关键词搜索结果冒充目录内容。 - */ -export async function listRealDirectoryContentsResult( - dirPath: string, - hostOverride?: DynamicBridge -): Promise { - if (!dirPath || !dirPath.trim()) return { entries: [], error: 'EMPTY_DIRECTORY_PATH' } - const targetDir = dirPath.trim() - - if (!hostOverride && isRealElectronHost()) { - const tree = await scanRealDirectoryTree(targetDir, 60) - const paths: string[] = [] - for (const s of tree.subdirs) { - if (s.path) paths.push(s.path) - } - for (const f of tree.files) { - if (f.path) paths.push(f.path) - } - if (paths.length > 0) return { entries: Array.from(new Set(paths)) } - } - - const listing = await listDirectoryViaFilesystem(targetDir, hostOverride) - if (!listing.ok) return { entries: [], error: listing.error } - if (listing.entries.length === 0) return { entries: [], error: DIRECTORY_EMPTY_OR_UNREADABLE } - return { entries: listing.entries.map(e => e.path) } -} - -/** - * 读取真实目录下的条目路径(保持旧签名:失败时返回空数组,需要失败原因请用 listRealDirectoryContentsResult) - */ -export async function listRealDirectoryContents( - dirPath: string, - hostOverride?: DynamicBridge -): Promise { - return (await listRealDirectoryContentsResult(dirPath, hostOverride)).entries -} - -/** - * 只列出目录的直接子项(子目录 + 直接位于该目录下的文件),用于文件夹预览、按目录改名等场景。 - * dir: 扫描结果中只保留 subdirs 与父目录等于 dirPath 的文件;扫描达到上限时 partial=true,由插件如实提示「仅显示部分」。 - */ -export async function listDirectChildren( - dirPath: string, - hostOverride?: DynamicBridge -): Promise { - if (!dirPath || !dirPath.trim()) return { entries: [], partial: false, error: 'EMPTY_DIRECTORY_PATH' } - const targetDir = dirPath.trim() - const scanLimit = 200 - const entries: RealIndexedFileEntry[] = [] - const seen = new Set() - const push = (entry: RealIndexedFileEntry) => { - const key = comparablePath(entry.path) - if (!entry.path || seen.has(key)) return - seen.add(key) - entries.push(entry) - } - - const { scan: tree, error } = await scanDirectoryTreeWithError(targetDir, { maxFiles: scanLimit, hostOverride }) - for (const s of tree.subdirs) { - if (!s.path || !isDirectChildPath(targetDir, s.path)) continue - push( - normalizeIndexedFileEntry({ - name: s.name || s.path.split(/[\\/]/).pop(), - path: s.path, - isDir: true, - size: s.totalBytes, - mtime: s.mtime - }) - ) - } - let directFileCount = 0 - for (const f of tree.files) { - if (!isDirectChildPath(targetDir, f.path)) continue - directFileCount++ - push(f) - } - // 宿主 total_matches 是全树文件数、subdirs[].file_count 是各子目录全树文件数,差值即直接子文件数; - // 拿到的直接子文件少于它就说明被 Top-N 截断了。计数不可用时按是否达到扫描上限判断 - const expectedDirectFiles = tree.totalFiles - tree.subdirs.reduce((sum, d) => sum + (Number(d.fileCount) || 0), 0) - const partial = - Number.isFinite(expectedDirectFiles) && expectedDirectFiles >= 0 - ? directFileCount < expectedDirectFiles - : tree.files.length >= scanLimit - if (entries.length > 0) { - return { entries, partial } - } - - if (tree.files.length > 0) { - // dir: 扫描只返回了深层文件(直接子文件被 Top-N 截掉),如实标注部分结果 - return { entries: [], partial: true, error: DIRECTORY_EMPTY_OR_UNREADABLE } - } - return { entries: [], partial: false, error: error || DIRECTORY_EMPTY_OR_UNREADABLE } -} - -/** - * 获取真实文件字节大小(优先用扫描结果里的大小,再走 filesystem_get_file_size);读不到时返回 0 - */ -export async function getRealFileSize( - filePath: string, - hostOverride?: DynamicBridge -): Promise { - if (!filePath) return 0 - if (!hostOverride && realFileSizeCache.has(filePath)) { - const cached = realFileSizeCache.get(filePath)! - if (cached > 0) return cached - } - const res = await callHostTransport('filesystem_get_file_size', { path: filePath }, hostOverride) - // 客户端返回 { success, size }(目录时 size 为 -1),旧的测试替身直接返回数字 - const size = typeof res.data === 'number' ? res.data : res.data?.size - if (res.ok && typeof size === 'number' && Number.isFinite(size) && size >= 0) { - realFileSizeCache.set(filePath, size) - return size - } - return 0 -} - -/** - * 在访达 / 资源管理器中定位并高亮文件或目录。 - * 定位失败直接返回 false,不能改用“打开”:对可执行文件那等于运行它。 - */ -export async function showRealItemInFolder( - fullPath: string, - hostOverride?: DynamicBridge -): Promise { - if (!fullPath) return false - const res = await callHostTransport('shell_show_item_in_folder', { fullPath }, hostOverride) - return res.ok -} - -/** - * 使用系统默认程序打开文件或目录 - */ -export async function openRealPath( - fullPath: string, - hostOverride?: DynamicBridge -): Promise { - if (!fullPath) return false - const res = await callHostTransport('shell_open_path', { fullPath }, hostOverride) - return res.ok -} - -/** - * 将真实文件或目录移入系统回收站(安全可恢复删除) - */ -export async function trashRealItem( - fullPath: string, - hostOverride?: DynamicBridge -): Promise<{ ok: boolean; error?: string; errorCode?: string; errorDetails?: Record }> { - if (!fullPath) return { ok: false, error: ipcStrings().pathEmpty } - const res = await callHostTransport('shell_trash_item', { fullPath }, hostOverride) - return { - ok: res.ok, - error: res.error, - ...(!res.ok && res.errorCode ? { errorCode: res.errorCode } : {}), - ...(!res.ok && res.errorDetails ? { errorDetails: res.errorDetails } : {}) - } -} - -export interface NativeInvocationResult { - ok: boolean - code: number - message: string - data?: T - error?: string - errorCode?: string - errorDetails?: Record -} - -export interface DllCapabilityResponse { - ok: boolean - code: number - data: T | null - message?: string - error?: string - errorCode?: string - errorDetails?: Record - pluginName: string - method: string - fromFallback?: boolean -} - -/** 声明式能力菜单项及其调用回执,供相同宿主协议的插件共用。 */ -export interface CapabilityActionItem { - id: string - title: string - subtitle: string - tag: string - method: string - params: Record -} - -export type PluginInvocationResult = Pick< - DllCapabilityResponse, 'ok' | 'pluginName' | 'method' | 'error' | 'errorCode' | 'errorDetails' | 'fromFallback' -> & { data?: unknown } - -/** 多个原生能力插件共用的参数边界校验;保护目标由各插件按自身业务提供。 */ -export function validateNativeCapabilityPayload( - method: string, - params: unknown, - forbiddenPattern: RegExp, - forbiddenReason: string -): { valid: boolean; error?: string } { - const s = ipcStrings() - if (typeof method !== 'string' || method.trim().length === 0) { - return { valid: false, error: s.invalidMethodEmpty } - } - if (method.length > 128 || !/^[A-Za-z0-9_]+$/.test(method.trim())) { - return { valid: false, error: s.invalidMethodFormat } - } - if (params === null || params === undefined || typeof params !== 'object' || Array.isArray(params)) { - return { valid: false, error: s.invalidParamsObject } - } - - const record = params as Record - for (const [key, val] of Object.entries(record)) { - if (typeof val === 'string') { - if (val.length > 4096) { - return { valid: false, error: s.paramTooLong(key) } - } - if (forbiddenPattern.test(val)) { - return { valid: false, error: `SECURITY_INTERCEPTED: ${forbiddenReason}` } - } - } else if (typeof val === 'number') { - if (!Number.isFinite(val) || val < -1000 || val > 100_000_000) { - return { valid: false, error: s.paramOutOfRange(key) } - } - } - } - - return { valid: true } -} - -export async function invokeDllPluginCapability( - pluginName: string, - method: string, - params: Record = {}, - hostBridge?: DynamicBridge, - offlineFallback?: () => T | Promise -): Promise> { - const s = ipcStrings() - if (!method || typeof method !== 'string' || method.trim().length === 0) { - return { - ok: false, - code: -1, - data: null, - message: s.methodParamEmpty, - error: s.invalidMethodType, - pluginName, - method: String(method || '') - } - } - - const trimmedMethod = method.trim() - - const unwrapDllRawPayload = (raw: unknown, unwrapDataProperty: boolean): DllCapabilityResponse => { - let parsed: DynamicBridge = raw - if (typeof raw === 'string') { - try { - parsed = JSON.parse(raw) - } catch { - throw new Error(s.malformedDllResponse) - } - } - if (parsed && typeof parsed === 'object') { - if ('error' in parsed && parsed.error !== undefined && parsed.error !== null && parsed.error !== '') { - const errMsg = `DLL_ERROR: ${String(parsed.error)}` - return { - ok: false, - code: typeof parsed.code === 'number' ? parsed.code : -1, - data: null, - message: errMsg, - error: errMsg, - ...extractIpcErrorMeta(parsed), - ...extractIpcErrorMeta(parsed.error), - pluginName, - method: trimmedMethod, - fromFallback: false - } - } - if ('ok' in parsed && parsed.ok === false) { - const errMsg = `DLL_ERROR: ${String(parsed.error || parsed.message || s.unknownDllError)}` - return { - ok: false, - code: typeof parsed.code === 'number' ? parsed.code : -1, - data: null, - message: errMsg, - error: errMsg, - ...extractIpcErrorMeta(parsed), - ...extractIpcErrorMeta(parsed.error), - pluginName, - method: trimmedMethod, - fromFallback: false - } - } - const dataPayload = unwrapDataProperty && 'data' in parsed && parsed.data !== undefined ? parsed.data : parsed - return { - ok: true, - code: typeof parsed.code === 'number' ? parsed.code : 0, - data: dataPayload as T, - message: typeof parsed.message === 'string' ? parsed.message : undefined, - pluginName, - method: trimmedMethod, - fromFallback: false - } - } - return { - ok: true, - code: 0, - data: (parsed ?? null) as T, - pluginName, - method: trimmedMethod, - fromFallback: false - } - } - - const wrapCaughtDllError = (err: unknown): DllCapabilityResponse => { - const message = err instanceof Error ? err.message : String(err) - if (message.startsWith('MALFORMED_DLL_RESPONSE:')) { - throw err - } - const errMsg = `NATIVE_CALL_FAILED: ${message}` - return { - ok: false, - code: -1, - data: null, - message: errMsg, - error: errMsg, - ...extractIpcErrorMeta(err), - pluginName, - method: trimmedMethod, - fromFallback: false - } - } - - if (hostBridge && typeof hostBridge.invokeNative === 'function') { - try { - const raw = await hostBridge.invokeNative(pluginName, trimmedMethod, params) - return unwrapDllRawPayload(raw, true) - } catch (err: unknown) { - return wrapCaughtDllError(err) - } - } - - const runtimeHost = (hostBridge ?? (globalThis as Record).ztools) as - | { dllplugin?: { call?: (plugin: string, fn: string, payload: unknown) => Promise | unknown } } - | undefined - - const callFn = runtimeHost?.dllplugin?.call - if (typeof callFn === 'function') { - try { - const raw = await callFn.call(runtimeHost?.dllplugin, pluginName, trimmedMethod, params) - return unwrapDllRawPayload(raw, false) - } catch (err: unknown) { - return wrapCaughtDllError(err) - } - } - - const ipcRes = await callHostTransport( - 'dllplugin_call', - { - plugin: pluginName, - func: trimmedMethod, - params - }, - hostBridge - ) - - if (ipcRes.ok && ipcRes.data !== undefined && ipcRes.data !== null) { - return unwrapDllRawPayload(ipcRes.data, false) - } - - const isExplicitTransportFailure = - typeof ipcRes.error === 'string' && - ipcRes.error.length > 0 && - ipcRes.error !== 'NO_WINDOW_ENV' && - !ipcRes.error.startsWith('METHOD_NOT_AVAILABLE:') - - if ( - isRealElectronHost(hostBridge) || - isRealElectronHost() || - Boolean((hostBridge as DynamicBridge)?.__isRealHost) || - isExplicitTransportFailure - ) { - const errMsg = - ipcRes.error || s.hostIpcFailed(pluginName, trimmedMethod) - return { - ok: false, - code: -1, - data: null, - message: errMsg, - error: errMsg, - ...(ipcRes.errorCode ? { errorCode: ipcRes.errorCode } : {}), - ...(ipcRes.errorDetails ? { errorDetails: ipcRes.errorDetails } : {}), - pluginName, - method: trimmedMethod, - fromFallback: false - } - } - - if (typeof offlineFallback === 'function') { - const fallbackData = await offlineFallback() - return { - ok: true, - code: 0, - data: fallbackData, - pluginName, - method: trimmedMethod, - fromFallback: true - } - } - - const unavailableMsg = s.hostUnavailable(pluginName, trimmedMethod) - return { - ok: false, - code: -1, - data: null, - message: unavailableMsg, - error: unavailableMsg, - ...(ipcRes.errorCode ? { errorCode: ipcRes.errorCode } : {}), - ...(ipcRes.errorDetails ? { errorDetails: ipcRes.errorDetails } : {}), - pluginName, - method: trimmedMethod, - fromFallback: true - } -} - -export function formatBytes(bytes: number, decimals = 1): string { - const num = Number(bytes) - if (!Number.isFinite(num) || num <= 0) return '0 B' - if (num < 1024) return `${Math.round(num)} B` - const units = ['B', 'KB', 'MB', 'GB', 'TB'] - let val = num - let idx = 0 - while (val >= 1024 && idx < units.length - 1) { - val /= 1024 - idx += 1 - } - const safeDecimals = Math.max(0, Math.floor(decimals)) - return `${val >= 100 ? val.toFixed(0) : val.toFixed(safeDecimals)} ${units[idx]}` -} - -export function joinWinPath(...segments: string[]): string { - return segments - .filter(s => typeof s === 'string' && s.trim().length > 0) - .map((s, i) => (i === 0 ? s.replace(/[\\/]+$/, '') : s.replace(/^[\\/]+|[\\/]+$/g, ''))) - .join('\\') -} - -export interface RealEnvPaths { - home: string - userProfile: string - appData: string - localAppData: string - temp: string - downloads: string - documents: string - desktop: string - pictures: string - videos: string - music: string -} - -export async function getRealEnvPaths(hostOverride?: DynamicBridge): Promise { - const [homeRaw, appData, downloads, documents, desktop, pictures, videos, music] = await Promise.all([ - getRealSystemPath('home', hostOverride), - getRealSystemPath('appData', hostOverride), - getRealSystemPath('downloads', hostOverride), - getRealSystemPath('documents', hostOverride), - getRealSystemPath('desktop', hostOverride), - getRealSystemPath('pictures', hostOverride), - getRealSystemPath('videos', hostOverride), - getRealSystemPath('music', hostOverride) - ]) - const home = homeRaw || 'C:\\Users\\Default' - const isPosix = home.startsWith('/') - const tempRes = hostOverride ? await getRealSystemPath('temp', hostOverride) : '' - if (isPosix) { - return { - home, - userProfile: home, - appData: appData || `${home}/Library/Application Support`, - localAppData: `${home}/Library/Application Support`, - temp: tempRes || '/tmp', - downloads: downloads || `${home}/Downloads`, - documents: documents || `${home}/Documents`, - desktop: desktop || `${home}/Desktop`, - pictures: pictures || `${home}/Pictures`, - videos: videos || `${home}/Videos`, - music: music || `${home}/Music` - } - } - return { - home, - userProfile: home, - appData: appData || `${home}\\AppData\\Roaming`, - localAppData: `${home}\\AppData\\Local`, - temp: tempRes || `${home}\\AppData\\Local\\Temp`, - downloads: downloads || `${home}\\Downloads`, - documents: documents || `${home}\\Documents`, - desktop: desktop || `${home}\\Desktop`, - pictures: pictures || `${home}\\Pictures`, - videos: videos || `${home}\\Videos`, - music: music || `${home}\\Music` - } -} - -export const resolveRealSpecialPaths = getRealEnvPaths - -export async function readRealDirectory( - dirPath: string, - hostOverride?: DynamicBridge -): Promise { - if (!dirPath) return [] - const tree = await scanRealDirectoryTree(dirPath, { maxFiles: 120, hostOverride }) - const entries: RealIndexedFileEntry[] = [] - for (const s of tree.subdirs) { - entries.push( - normalizeIndexedFileEntry({ - name: s.name, - path: s.path, - isDir: true, - isDirectory: true, - size: s.totalBytes, - mtime: s.mtime - }) - ) - } - for (const f of tree.files) { - entries.push(f) - } - // scanRealDirectoryTree 已在 dir: 扫描无结果时退回一级目录读取;仍为空即目录不存在 / 为空 / 无权限,如实返回空列表 - return entries -} - -export async function moveRealFilesToTrash( - paths: string[], - hostOverride?: DynamicBridge -): Promise<{ - ok: boolean - trashedCount: number - deletedCount: number - failedPaths: string[] - error?: string -}> { - let deletedCount = 0 - const failedPaths: string[] = [] - let lastError: string | undefined - for (const p of paths) { - if (!p) continue - const res = await trashRealItem(p, hostOverride) - if (res.ok) { - deletedCount += 1 - } else { - failedPaths.push(p) - if (res.error) lastError = res.error - } - } - return { - ok: deletedCount > 0 || paths.length === 0, - trashedCount: deletedCount, - deletedCount, - failedPaths, - error: lastError - } -} - -const CAPABILITY_TO_PLUGIN_MAP: Record = { - 'mover.relocateWithJunction': { plugin: 'MoverPlugin', func: 'relocateWithJunction' }, - 'mover.scanCandidates': { plugin: 'MoverPlugin', func: 'scanCandidates' }, - 'recovery.restoreFile': { plugin: 'DataRecoveryPlugin', func: 'restoreFile' }, - 'recovery.scanDeletedFiles': { plugin: 'DataRecoveryPlugin', func: 'scanDeletedFiles' }, - 'shredder.secureWipeFile': { plugin: 'ShredderPlugin', func: 'secureWipeFile' }, - 'shredder.scanCandidates': { plugin: 'ShredderPlugin', func: 'scanCandidates' }, - 'backup.createSnapshotArchive': { plugin: 'SystemBackupPlugin', func: 'createSnapshotArchive' }, - 'backup.restoreSnapshotArchive': { plugin: 'SystemBackupPlugin', func: 'restoreSnapshotArchive' }, - 'backup.scanSnapshots': { plugin: 'SystemBackupPlugin', func: 'scanSnapshots' }, - 'sqlite.execute': { plugin: 'SqlitePlugin', func: 'execute' }, - 'sqlite.query': { plugin: 'SqlitePlugin', func: 'executeQuery' }, - 'sqlite.inspectWorkspace': { plugin: 'SqlitePlugin', func: 'inspectWorkspace' } -} - -export async function invokeHostCapability( - capability: string, - params: Record = {}, - hostOverride?: DynamicBridge -): Promise> { - const normalizedMethod = capability.replace(/\./g, '_') - - // 若测试显式注入了对应 normalizedMethod 的 mock 函数,优先调用测试桩 - if (hostOverride && typeof hostOverride[normalizedMethod] === 'function') { - const mockRes = await callHostTransport(normalizedMethod, params, hostOverride) - return { - ok: mockRes.ok, - code: mockRes.ok ? 0 : -1, - message: mockRes.ok ? 'OK' : mockRes.error || ipcStrings().callFailed, - data: mockRes.data, - error: mockRes.error, - ...(!mockRes.ok && mockRes.errorCode ? { errorCode: mockRes.errorCode } : {}), - ...(!mockRes.ok && mockRes.errorDetails ? { errorDetails: mockRes.errorDetails } : {}) - } - } - - if (capability === 'system.info') { - const drives = await probeRealDiskDrives(['C', 'D', 'E', 'F'], hostOverride) - return { - ok: true, - code: 0, - message: 'OK', - data: { - storage: drives.map(d => ({ - mount: d.drive, - fs: d.drive, - size: d.totalBytes, - total: d.totalBytes, - used: d.usedBytes, - available: d.availableBytes, - free: d.availableBytes, - percent: d.usagePercent - })) - } as unknown as T - } - } - if (capability === 'filesystem.deleteItem') { - const targetPath = String(params.path || params.fullPath || '') - const tr = await trashRealItem(targetPath, hostOverride) - const s = ipcStrings() - return { - ok: tr.ok, - code: tr.ok ? 0 : -1, - message: tr.ok ? s.movedToTrash : tr.error || s.deleteFailed, - error: tr.error, - ...(!tr.ok && tr.errorCode ? { errorCode: tr.errorCode } : {}), - ...(!tr.ok && tr.errorDetails ? { errorDetails: tr.errorDetails } : {}) - } - } - if (capability === 'system.showItemInFolder') { - const targetPath = String(params.path || params.fullPath || '') - const s = ipcStrings() - if (!targetPath) { - return { ok: false, code: -1, message: s.revealFailed } - } - const res = await callHostTransport('shell_show_item_in_folder', { fullPath: targetPath }, hostOverride) - return { - ok: res.ok, - code: res.ok ? 0 : -1, - message: res.ok ? s.revealedInFolder : res.error || s.revealFailed, - ...(!res.ok && res.error ? { error: res.error } : {}), - ...(!res.ok && res.errorCode ? { errorCode: res.errorCode } : {}), - ...(!res.ok && res.errorDetails ? { errorDetails: res.errorDetails } : {}) - } - } - if (capability === 'filesystem.openItem' || capability === 'system.openUrl') { - const target = String(params.path || params.url || params.fullPath || '') - const method = capability === 'system.openUrl' ? 'shell_open_external' : 'shell_open_path' - const res = await callHostTransport( - method, - capability === 'system.openUrl' ? { url: target } : { fullPath: target }, - hostOverride - ) - const s = ipcStrings() - return { - ok: res.ok, - code: res.ok ? 0 : -1, - message: res.ok ? s.opened : res.error || s.openFailed, - data: res.data, - error: res.error, - ...(!res.ok && res.errorCode ? { errorCode: res.errorCode } : {}), - ...(!res.ok && res.errorDetails ? { errorDetails: res.errorDetails } : {}) - } - } - - const pluginMapping = CAPABILITY_TO_PLUGIN_MAP[capability] - if (pluginMapping) { - const dllRes = await invokePluginService( - pluginMapping.plugin, - pluginMapping.func, - params, - hostOverride - ) - if (dllRes.ok) return dllRes - if (hostOverride) { - const fallbackMock = await callHostTransport(normalizedMethod, params, hostOverride) - if (fallbackMock.ok) { - return { - ok: true, - code: 0, - message: 'OK', - data: fallbackMock.data - } - } - } - return dllRes - } - - const res = await callHostTransport(normalizedMethod, params, hostOverride) - return { - ok: res.ok, - code: res.ok ? 0 : -1, - message: res.ok ? 'OK' : res.error || ipcStrings().callFailed, - data: res.data, - error: res.error, - ...(!res.ok && res.errorCode ? { errorCode: res.errorCode } : {}), - ...(!res.ok && res.errorDetails ? { errorDetails: res.errorDetails } : {}) - } -} - -export async function invokePluginService( - pluginName: string, - action: string, - params: Record = {}, - hostOverride?: DynamicBridge -): Promise> { - const s = ipcStrings() - // 1. 若测试注入了专门拦截 plugin_invoke 的 mock,支持调用 - if (hostOverride && typeof hostOverride.plugin_invoke === 'function') { - const mockRes = await callHostTransport( - 'plugin_invoke', - { plugin: pluginName, action, params }, - hostOverride - ) - return { - ok: mockRes.ok, - code: mockRes.ok ? 0 : -1, - message: mockRes.ok ? 'OK' : mockRes.error || s.pluginCallNotReady, - data: mockRes.data, - error: mockRes.error, - ...(!mockRes.ok && mockRes.errorCode ? { errorCode: mockRes.errorCode } : {}), - ...(!mockRes.ok && mockRes.errorDetails ? { errorDetails: mockRes.errorDetails } : {}) - } - } - - // 2. 优先走真实 Electron IPC 的 dllplugin_call 通道 - const dllRes = await callHostTransport( - 'dllplugin_call', - { plugin: pluginName, func: action, params }, - hostOverride - ) - if (dllRes.ok) { - const inner = dllRes.data - if (inner && typeof inner === 'object' && typeof inner.error === 'string' && inner.error.length > 0 && inner.ok !== true) { - return { - ok: false, - code: -1, - message: inner.error, - error: inner.error, - ...extractIpcErrorMeta(inner) - } - } - return { - ok: true, - code: 0, - message: 'OK', - data: inner as T - } - } - - // 3. 兼容单元测试中通过 transport.call('plugin_invoke') 注入的测试桩 - if (hostOverride) { - const legacyRes = await callHostTransport( - 'plugin_invoke', - { plugin: pluginName, action, params }, - hostOverride - ) - if (legacyRes.ok) { - return { - ok: true, - code: 0, - message: 'OK', - data: legacyRes.data - } - } - } - - // 4. 兼容旧版 globalThis.ztools.dllplugin.call - const g = globalThis as DynamicBridge - if (!hostOverride && typeof g?.ztools?.dllplugin?.call === 'function') { - try { - const raw = await g.ztools.dllplugin.call(pluginName, action, params) - if (raw && typeof raw === 'object' && raw.ok === false) { - return { - ok: false, - code: -1, - message: String(raw.error || s.callFailed), - error: String(raw.error || s.callFailed), - ...extractIpcErrorMeta(raw), - ...extractIpcErrorMeta(raw.error) - } - } - const data = raw && typeof raw === 'object' && 'data' in raw ? raw.data : raw - return { ok: true, code: 0, message: 'OK', data: data as T } - } catch (err: DynamicBridge) { - return { - ok: false, - code: -1, - message: err instanceof Error ? err.message : String(err), - error: err instanceof Error ? err.message : String(err), - ...extractIpcErrorMeta(err) - } - } - } - - return { - ok: false, - code: -1, - message: dllRes.error || s.pluginCallNotReady, - error: dllRes.error || s.pluginCallNotReady, - ...(dllRes.errorCode ? { errorCode: dllRes.errorCode } : {}), - ...(dllRes.errorDetails ? { errorDetails: dllRes.errorDetails } : {}) - } -} - -const SHA256_K = new Uint32Array([ - 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, - 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, - 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, - 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, - 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, - 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, - 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, - 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2 -]) - -function rotr32(x: number, n: number): number { - return (x >>> n) | (x << (32 - n)) -} - -/** - * 标准 FIPS 180-4 SHA-256 真实字节摘要算法(返回 64 位小写 Hex) - */ -export function computeRealSha256Hex(input: string | Uint8Array): string { - const bytes = - typeof input === 'string' ? new TextEncoder().encode(input) : new Uint8Array(input || []) - const bitLen = bytes.length * 8 - const padLen = ((bytes.length + 9 + 63) & ~63) - const buf = new Uint8Array(padLen) - buf.set(bytes, 0) - buf[bytes.length] = 0x80 - const view = new DataView(buf.buffer) - view.setUint32(padLen - 8, Math.floor(bitLen / 0x100000000), false) - view.setUint32(padLen - 4, bitLen >>> 0, false) - - let h0 = 0x6a09e667 - let h1 = 0xbb67ae85 - let h2 = 0x3c6ef372 - let h3 = 0xa54ff53a - let h4 = 0x510e527f - let h5 = 0x9b05688c - let h6 = 0x1f83d9ab - let h7 = 0x5be0cd19 - - const w = new Uint32Array(64) - for (let offset = 0; offset < padLen; offset += 64) { - for (let i = 0; i < 16; i++) { - w[i] = view.getUint32(offset + i * 4, false) - } - for (let i = 16; i < 64; i++) { - const s0 = rotr32(w[i - 15], 7) ^ rotr32(w[i - 15], 18) ^ (w[i - 15] >>> 3) - const s1 = rotr32(w[i - 2], 17) ^ rotr32(w[i - 2], 19) ^ (w[i - 2] >>> 10) - w[i] = (w[i - 16] + s0 + w[i - 7] + s1) >>> 0 - } - - let a = h0 - let b = h1 - let c = h2 - let d = h3 - let e = h4 - let f = h5 - let g = h6 - let h = h7 - - for (let i = 0; i < 64; i++) { - const S1 = rotr32(e, 6) ^ rotr32(e, 11) ^ rotr32(e, 25) - const ch = (e & f) ^ (~e & g) - const temp1 = (h + S1 + ch + SHA256_K[i] + w[i]) >>> 0 - const S0 = rotr32(a, 2) ^ rotr32(a, 13) ^ rotr32(a, 22) - const maj = (a & b) ^ (a & c) ^ (b & c) - const temp2 = (S0 + maj) >>> 0 - - h = g - g = f - f = e - e = (d + temp1) >>> 0 - d = c - c = b - b = a - a = (temp1 + temp2) >>> 0 - } - - h0 = (h0 + a) >>> 0 - h1 = (h1 + b) >>> 0 - h2 = (h2 + c) >>> 0 - h3 = (h3 + d) >>> 0 - h4 = (h4 + e) >>> 0 - h5 = (h5 + f) >>> 0 - h6 = (h6 + g) >>> 0 - h7 = (h7 + h) >>> 0 - } - - return [h0, h1, h2, h3, h4, h5, h6, h7] - .map(v => (v >>> 0).toString(16).padStart(8, '0')) - .join('') -} - -/** - * 读取本地文件真实字节并计算标准 SHA-256:宿主 filesearch_sha256(只接受 path 字段)优先,Windows 上再试 FileComparePlugin。 - * 都拿不到时返回空字符串,由调用方提示失败;不再把文件按 UTF-8 文本读出来再算(二进制文件会算出错误的值)。 - */ -export async function computeRealFileSha256( - filePath: string, - hostOverride?: DynamicBridge -): Promise { - if (!filePath || !filePath.trim()) return '' - const target = filePath.trim() - - const shaRes = await callHostTransport('filesearch_sha256', { fullPath: target }, hostOverride) - if (shaRes.ok && shaRes.data) { - const hash = typeof shaRes.data === 'string' ? shaRes.data : String(shaRes.data?.sha256 || shaRes.data?.hash || '') - if (/^[0-9a-f]{64}$/i.test(hash)) return hash.toLowerCase() - } - - const dllRes = await invokePluginService('FileComparePlugin', 'computeFileSha256', { path: target }, hostOverride) - if (dllRes.ok && dllRes.data) { - const hash = typeof dllRes.data === 'string' ? dllRes.data : String(dllRes.data?.sha256 || dllRes.data?.hash || '') - if (/^[0-9a-f]{64}$/i.test(hash)) return hash.toLowerCase() - } - - return '' -} - -export async function readRealClipboardText(hostOverride?: DynamicBridge): Promise { - const res = await callHostTransport('clipboard_read_text', {}, hostOverride) - if (res.ok && res.data !== undefined && res.data !== null) { - if (typeof res.data === 'string') return res.data - if (typeof res.data?.text === 'string') return res.data.text - } - try { - if (typeof navigator !== 'undefined' && navigator.clipboard?.readText) { - return await navigator.clipboard.readText() - } - } catch { - // ignore - } - return '' -} - -export async function writeRealClipboardText(text: string, hostOverride?: DynamicBridge): Promise { - const payload = { text: String(text || '') } - const res = await callHostTransport('clipboard_copy_text', payload, hostOverride) - if (res.ok) return true - try { - if (typeof navigator !== 'undefined' && navigator.clipboard?.writeText) { - await navigator.clipboard.writeText(String(text || '')) - return true - } - } catch { - // ignore - } - return false -} - -export async function showRealToast( - title: string, - style: 'success' | 'failure' | 'info' = 'info' -): Promise { - try { - const { showToast, Toast } = await import('@ztools/declarative-ui') - await showToast({ - title, - style: - style === 'success' - ? Toast.Style.Success - : style === 'failure' - ? Toast.Style.Failure - : Toast.Style.Animated - }) - } catch { - // ignore - } -} - diff --git a/extensions/data-recovery/src/recycle-bin.ts b/extensions/data-recovery/src/recycle-bin.ts deleted file mode 100644 index 8e3e1e2..0000000 --- a/extensions/data-recovery/src/recycle-bin.ts +++ /dev/null @@ -1,301 +0,0 @@ -/** - * Windows $Recycle.Bin\\$I* 二进制元数据头解析器与恢复目标安全校验器 - * - * 格式规范(Windows Vista / 7 / 8 / 10 / 11): - * - Header v1 (Vista / Win7 / Win8): - * [0..7] uint64le version = 1 - * [8..15] uint64le original file size in bytes - * [16..23] uint64le deletion timestamp (Windows FILETIME: 100ns intervals since 1601-01-01 UTC) - * [24..543] 520 bytes fixed UTF-16LE NUL-terminated original path (260 WCHARs) - * - Header v2 (Windows 10 / 11): - * [0..7] uint64le version = 2 - * [8..15] uint64le original file size in bytes - * [16..23] uint64le deletion timestamp (Windows FILETIME) - * [24..27] uint32le path length in UTF-16 code units (including trailing NUL) - * [28..] pathLen * 2 bytes variable-length UTF-16LE original path - */ - -import { t } from "./i18n.js"; - -/** Windows FILETIME 纪元(1601-01-01)到 Unix 纪元(1970-01-01)的 100 纳秒差值 */ -const FILETIME_EPOCH_DIFF_100NS = 116444736000000000n; -const TICKS_PER_MS = 10000n; -/** 合理时间上限(2200-01-01 UTC) */ -const MAX_REASONABLE_UNIX_MS = Date.UTC(2200, 0, 1); - -/** v1 路径区固定最大 UTF-16 code unit 数量(MAX_PATH = 260) */ -const V1_MAX_PATH_CHARS = 260; -/** v2 变长路径最大允许 UTF-16 code unit 数量(NTFS 扩展路径上限 32768) */ -const V2_MAX_PATH_CHARS = 32768; - -export const FORBIDDEN_TARGET_PATTERN = - /(^|[\\/])(Windows|System32|SysWOW64|Program Files|Program Files \(x86\)|\.\.)($|[\\/])/i; - -export interface ParsedRecycleBinInfoSuccess { - ok: true; - headerVersion: 1 | 2; - originalSizeBytes: number; - deletedAtMs: number; - originalPath: string; - originalName: string; -} - -export interface ParsedRecycleBinInfoFailure { - ok: false; - errorCode: - | "INVALID_INPUT" - | "TRUNCATED_HEADER" - | "UNSUPPORTED_VERSION" - | "INVALID_PATH_LENGTH" - | "CORRUPT_PATH"; - error: string; -} - -export type ParsedRecycleBinInfo = ParsedRecycleBinInfoSuccess | ParsedRecycleBinInfoFailure; - -export interface RecoveryTargetValidationResult { - ok: boolean; - errorCode?: "EMPTY_TARGET" | "FORBIDDEN_TARGET" | "SAME_SOURCE_DRIVE"; - sourceDrive?: string; - targetDrive?: string; - error?: string; -} - -/** - * 将 Windows FILETIME(1601-01-01 起百纳秒整数)转换为 Unix 毫秒时间戳。 - * 输入为 0 或超出合理时间范围时返回 0(不编造伪时间)。 - */ -export function filetimeToUnixMs(filetime: bigint): number { - if (filetime <= FILETIME_EPOCH_DIFF_100NS) { - return 0; - } - const unixMsBig = (filetime - FILETIME_EPOCH_DIFF_100NS) / TICKS_PER_MS; - if (unixMsBig <= 0n || unixMsBig > BigInt(MAX_REASONABLE_UNIX_MS)) { - return 0; - } - return Number(unixMsBig); -} - -/** - * 将标准 Base64 字符串解码为 Uint8Array(纯 JS 实现,兼容浏览器渲染层与 Node 测试环境)。 - */ -export function decodeBase64ToBytes(base64: string): Uint8Array | null { - if (typeof base64 !== "string") return null; - const cleaned = base64.replace(/\s+/g, ""); - if (cleaned.length === 0) return new Uint8Array(0); - if (cleaned.length % 4 !== 0 || !/^[A-Za-z0-9+/]*={0,2}$/.test(cleaned)) { - return null; - } - const alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; - let padding = 0; - if (cleaned.endsWith("==")) padding = 2; - else if (cleaned.endsWith("=")) padding = 1; - - const outLen = (cleaned.length / 4) * 3 - padding; - const out = new Uint8Array(outLen); - let outIdx = 0; - - for (let i = 0; i < cleaned.length; i += 4) { - const c0 = alphabet.indexOf(cleaned[i]); - const c1 = alphabet.indexOf(cleaned[i + 1]); - const c2 = cleaned[i + 2] === "=" ? 0 : alphabet.indexOf(cleaned[i + 2]); - const c3 = cleaned[i + 3] === "=" ? 0 : alphabet.indexOf(cleaned[i + 3]); - if (c0 < 0 || c1 < 0 || c2 < 0 || c3 < 0) return null; - - const triple = (c0 << 18) | (c1 << 12) | (c2 << 6) | c3; - if (outIdx < outLen) out[outIdx++] = (triple >> 16) & 0xff; - if (outIdx < outLen) out[outIdx++] = (triple >> 8) & 0xff; - if (outIdx < outLen) out[outIdx++] = triple & 0xff; - } - return out; -} - -/** - * 从小端 UTF-16LE 字节片段解码字符串,遇到第一个 0x0000 终止符停止。 - */ -function decodeUtf16LeUntilNul(view: DataView, byteOffset: number, charCount: number): string { - const units: number[] = []; - for (let i = 0; i < charCount; i += 1) { - const codeUnit = view.getUint16(byteOffset + i * 2, true); - if (codeUnit === 0) break; - units.push(codeUnit); - } - // 分块 String.fromCharCode,避免超长路径(> 8192 字符)触发调用栈溢出 - let result = ""; - const chunkSize = 4096; - for (let i = 0; i < units.length; i += chunkSize) { - result += String.fromCharCode(...units.slice(i, i + chunkSize)); - } - return result; -} - -/** - * 解析 Windows `$Recycle.Bin\\$I*` 二进制元数据文件。 - * 严格支持 v1(Vista/Win7/Win8 24 字节头 + 520 字节固定路径)与 v2(Win10/Win11 28 字节头 + 变长 UTF-16LE 路径), - * 对截断头、非法版本、越界长度与损坏路径一律显式拒绝。 - */ -export function parseRecycleBinInfoFile(bytes: Uint8Array): ParsedRecycleBinInfo { - if (!(bytes instanceof Uint8Array)) { - return { ok: false, errorCode: "INVALID_INPUT", error: "Expected Uint8Array for $I metadata" }; - } - if (bytes.byteLength < 26) { - return { - ok: false, - errorCode: "TRUNCATED_HEADER", - error: `Recycle Bin $I header too short (${bytes.byteLength} bytes)` - }; - } - - const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength); - const version = view.getBigUint64(0, true); - const rawSize = view.getBigUint64(8, true); - const rawFiletime = view.getBigUint64(16, true); - - if (rawSize > BigInt(Number.MAX_SAFE_INTEGER)) { - return { - ok: false, - errorCode: "CORRUPT_PATH", - error: "Original file size in $I header exceeds safe integer range" - }; - } - - const originalSizeBytes = Number(rawSize); - const deletedAtMs = filetimeToUnixMs(rawFiletime); - - let headerVersion: 1 | 2; - let originalPath = ""; - - if (version === 1n) { - headerVersion = 1; - // v1 规范总长为 544 字节(24 字节头 + 520 字节固定 UTF-16LE 路径区);至少需含 24 字节头 + 1 个 UTF-16 字符 - const availableChars = Math.floor((bytes.byteLength - 24) / 2); - if (availableChars < 1) { - return { - ok: false, - errorCode: "TRUNCATED_HEADER", - error: "v1 $I file missing UTF-16LE path payload" - }; - } - const charsToRead = Math.min(V1_MAX_PATH_CHARS, availableChars); - originalPath = decodeUtf16LeUntilNul(view, 24, charsToRead); - } else if (version === 2n) { - headerVersion = 2; - if (bytes.byteLength < 30) { - return { - ok: false, - errorCode: "TRUNCATED_HEADER", - error: `v2 $I header truncated (${bytes.byteLength} bytes)` - }; - } - const pathCharLen = view.getUint32(24, true); - if (pathCharLen < 1 || pathCharLen > V2_MAX_PATH_CHARS) { - return { - ok: false, - errorCode: "INVALID_PATH_LENGTH", - error: `v2 $I path length out of range: ${pathCharLen}` - }; - } - const requiredBytes = 28 + pathCharLen * 2; - if (requiredBytes > bytes.byteLength) { - return { - ok: false, - errorCode: "TRUNCATED_HEADER", - error: `v2 $I payload truncated: expected ${requiredBytes} bytes, got ${bytes.byteLength}` - }; - } - originalPath = decodeUtf16LeUntilNul(view, 28, pathCharLen); - } else { - return { - ok: false, - errorCode: "UNSUPPORTED_VERSION", - error: `Unsupported $I header version: ${version.toString()}` - }; - } - - const normalizedPath = originalPath.trim(); - if (!normalizedPath || /[\u0000-\u001f]/.test(normalizedPath)) { - return { - ok: false, - errorCode: "CORRUPT_PATH", - error: "Decoded original path in $I metadata is empty or contains control characters" - }; - } - - const segments = normalizedPath.split(/[\\/]+/).filter(Boolean); - const originalName = segments.length > 0 ? segments[segments.length - 1] : normalizedPath; - - return { - ok: true, - headerVersion, - originalSizeBytes, - deletedAtMs, - originalPath: normalizedPath, - originalName - }; -} - -/** - * 从路径或卷标识中提取规范大写 Windows 盘符(如 "C")。 - * 支持格式:"C:\\path"、"c:/path"、"\\\\.\\C:"、"\\\\?\\D:\\dir"、"E:"、"F"。 - */ -export function extractDriveLetter(pathOrVolume: string): string | null { - const raw = String(pathOrVolume || "").trim(); - if (!raw) return null; - const extendedMatch = raw.match(/^\\\\[.?]\\([A-Za-z]):(?:[\\/]|$)/); - if (extendedMatch) return extendedMatch[1].toUpperCase(); - const driveMatch = raw.match(/^([A-Za-z]):(?:[\\/]|$)/); - if (driveMatch) return driveMatch[1].toUpperCase(); - const singleLetterMatch = raw.match(/^([A-Za-z])$/); - if (singleLetterMatch) return singleLetterMatch[1].toUpperCase(); - return null; -} - -/** - * 恢复输出目录硬校验: - * 1. 严禁为空; - * 2. 严禁落在系统目录或包含 `..` 路径穿越; - * 3. **严禁落在任何源待恢复分区所在盘符**(防止恢复写入覆盖尚未读取的待恢复扇区)。 - */ -export function validateRecoveryOutputTarget( - sourcePathsOrDrives: string | string[], - targetDir: string -): RecoveryTargetValidationResult { - const normalizedTarget = String(targetDir || "").trim().replace(/[\\/]+$/, ""); - if (!normalizedTarget) { - return { - ok: false, - errorCode: "EMPTY_TARGET", - error: t("desktopUnavailable") - }; - } - - if (FORBIDDEN_TARGET_PATTERN.test(normalizedTarget)) { - return { - ok: false, - errorCode: "FORBIDDEN_TARGET", - error: t("forbiddenReason") - }; - } - - const targetDrive = extractDriveLetter(normalizedTarget); - const sourceList = Array.isArray(sourcePathsOrDrives) ? sourcePathsOrDrives : [sourcePathsOrDrives]; - if (targetDrive) { - for (const src of sourceList) { - const srcDrive = extractDriveLetter(src); - if (srcDrive && srcDrive === targetDrive) { - return { - ok: false, - errorCode: "SAME_SOURCE_DRIVE", - sourceDrive: srcDrive, - targetDrive, - error: t("sameDriveTargetReason", { drive: targetDrive }) - }; - } - } - } - - return { - ok: true, - ...(targetDrive ? { targetDrive } : {}) - }; -} diff --git a/extensions/data-recovery/tests/data-recovery.host.test.mjs b/extensions/data-recovery/tests/data-recovery.host.test.mjs deleted file mode 100644 index 6941995..0000000 --- a/extensions/data-recovery/tests/data-recovery.host.test.mjs +++ /dev/null @@ -1,474 +0,0 @@ -import test from 'node:test' -import assert from 'node:assert/strict' -import { setRuntimeLocale } from '@ztools/declarative-ui' - -setRuntimeLocale('zh-CN') -const dataRecovery = await import('../dist/logic.js') - -const FILETIME_EPOCH_DIFF_100NS = 116444736000000000n - -function unixMsToFiletime(ms) { - return BigInt(ms) * 10000n + FILETIME_EPOCH_DIFF_100NS -} - -/** 构造规范的 Windows $Recycle.Bin $I v1 (544 bytes: 24 字节头 + 520 字节固定 UTF-16LE 路径) */ -function buildRecycleInfoV1({ originalSize, deletedAtMs, originalPath }) { - const buf = new Uint8Array(544) - const view = new DataView(buf.buffer) - view.setBigUint64(0, 1n, true) - view.setBigUint64(8, BigInt(originalSize), true) - view.setBigUint64(16, unixMsToFiletime(deletedAtMs), true) - for (let i = 0; i < originalPath.length && i < 259; i += 1) { - view.setUint16(24 + i * 2, originalPath.charCodeAt(i), true) - } - return buf -} - -/** 构造规范的 Windows $Recycle.Bin $I v2 (28 字节头 + 变长 UTF-16LE 路径 + 尾 NUL) */ -function buildRecycleInfoV2({ originalSize, deletedAtMs, originalPath }) { - const pathCharLen = originalPath.length + 1 - const buf = new Uint8Array(28 + pathCharLen * 2) - const view = new DataView(buf.buffer) - view.setBigUint64(0, 2n, true) - view.setBigUint64(8, BigInt(originalSize), true) - view.setBigUint64(16, unixMsToFiletime(deletedAtMs), true) - view.setUint32(24, pathCharLen, true) - for (let i = 0; i < originalPath.length; i += 1) { - view.setUint16(28 + i * 2, originalPath.charCodeAt(i), true) - } - view.setUint16(28 + originalPath.length * 2, 0, true) - return buf -} - -function toBase64(bytes) { - return Buffer.from(bytes).toString('base64') -} - -function createRealHostStub(handlers = {}) { - const calls = [] - const dispatch = async (method, params) => { - calls.push({ channel: method, payload: params }) - if (typeof handlers[method] === 'function') { - return await handlers[method](params) - } - if (method in handlers) { - return handlers[method] - } - throw new Error(`CHANNEL_NOT_IMPLEMENTED: ${method}`) - } - - const stub = { - __isRealHost: true, - calls, - transport: { call: dispatch } - } - - for (const key of Object.keys(handlers)) { - stub[key] = (params) => dispatch(key, params) - } - - return stub -} - -test('data-recovery $I 二进制解析: 支持 Vista/Win7 v1 (24B 头 + 中文路径 + FILETIME)', () => { - const deletedAtMs = Date.UTC(2026, 4, 15, 8, 30, 45) - const originalPath = 'D:\\工作文档\\2026财务报表\\季度总结.xlsx' - const raw = buildRecycleInfoV1({ originalSize: 123456, deletedAtMs, originalPath }) - - const parsed = dataRecovery.parseRecycleBinInfoFile(raw) - assert.equal(parsed.ok, true) - assert.equal(parsed.headerVersion, 1) - assert.equal(parsed.originalSizeBytes, 123456) - assert.equal(parsed.deletedAtMs, deletedAtMs) - assert.equal(parsed.originalPath, originalPath) - assert.equal(parsed.originalName, '季度总结.xlsx') -}) - -test('data-recovery $I 二进制解析: 支持 Win10/11 v2 (变长 UTF-16LE 中文路径与超长路径 >300 字符)', () => { - const deletedAtMs = Date.UTC(2026, 10, 27, 10, 20, 30) - const longDir = '归档目录_'.repeat(65) - const originalPath = `E:\\项目资料\\${longDir}\\核心设计方案_最终版.docx` - assert.ok(originalPath.length > 320, '路径应超过传统 MAX_PATH=260 限制') - - const raw = buildRecycleInfoV2({ originalSize: 987654321, deletedAtMs, originalPath }) - const parsed = dataRecovery.parseRecycleBinInfoFile(raw) - assert.equal(parsed.ok, true) - assert.equal(parsed.headerVersion, 2) - assert.equal(parsed.originalSizeBytes, 987654321) - assert.equal(parsed.deletedAtMs, deletedAtMs) - assert.equal(parsed.originalPath, originalPath) - assert.equal(parsed.originalName, '核心设计方案_最终版.docx') -}) - -test('data-recovery $I 二进制解析: 严格拒绝截断头、未知版本、越界长度与空路径损坏头', () => { - // 1. 截断过短 - const tooShort = new Uint8Array(16) - const resShort = dataRecovery.parseRecycleBinInfoFile(tooShort) - assert.equal(resShort.ok, false) - assert.equal(resShort.errorCode, 'TRUNCATED_HEADER') - - // 2. 未知版本 (version = 99) - const badVer = new Uint8Array(64) - new DataView(badVer.buffer).setBigUint64(0, 99n, true) - const resVer = dataRecovery.parseRecycleBinInfoFile(badVer) - assert.equal(resVer.ok, false) - assert.equal(resVer.errorCode, 'UNSUPPORTED_VERSION') - - // 3. v2 声称路径长度超出实际字节缓冲区(截断损坏) - const truncatedV2 = new Uint8Array(40) - const viewTrunc = new DataView(truncatedV2.buffer) - viewTrunc.setBigUint64(0, 2n, true) - viewTrunc.setBigUint64(8, 1024n, true) - viewTrunc.setBigUint64(16, unixMsToFiletime(Date.UTC(2026, 0, 1)), true) - viewTrunc.setUint32(24, 50, true) // 需要 28 + 100 = 128 bytes,但只有 40 bytes - const resTruncV2 = dataRecovery.parseRecycleBinInfoFile(truncatedV2) - assert.equal(resTruncV2.ok, false) - assert.equal(resTruncV2.errorCode, 'TRUNCATED_HEADER') - - // 4. v2 路径长度为 0 - const zeroLenV2 = new Uint8Array(32) - const viewZero = new DataView(zeroLenV2.buffer) - viewZero.setBigUint64(0, 2n, true) - viewZero.setUint32(24, 0, true) - const resZero = dataRecovery.parseRecycleBinInfoFile(zeroLenV2) - assert.equal(resZero.ok, false) - assert.equal(resZero.errorCode, 'INVALID_PATH_LENGTH') - - // 5. v1 空路径 - const emptyPathV1 = new Uint8Array(544) - new DataView(emptyPathV1.buffer).setBigUint64(0, 1n, true) - const resEmptyPath = dataRecovery.parseRecycleBinInfoFile(emptyPathV1) - assert.equal(resEmptyPath.ok, false) - assert.equal(resEmptyPath.errorCode, 'CORRUPT_PATH') -}) - -test('data-recovery 快速回收站: 精确还原 $I 元数据,跨用户 SID 权限拒绝如实提示且不造假', async () => { - const deletedMs = Date.UTC(2026, 8, 1, 12, 0, 0) - const infoBytes = buildRecycleInfoV2({ - originalSize: 20480, - deletedAtMs: deletedMs, - originalPath: 'D:\\重要合同\\年度合作协议.pdf' - }) - - const host = createRealHostStub({ - system_get_path: ({ name }) => (name === 'desktop' ? 'E:\\Users\\Tester\\Desktop' : ''), - system_get_disk_usage: ({ drive }) => { - if (drive === 'D:\\') return { total: 1000, used: 500, available: 500 } - throw new Error('DRIVE_NOT_READY') - }, - filesystem_get_directory_contents: ({ path }) => { - if (path === 'D:\\$Recycle.Bin') { - return { - entries: [ - { name: 'S-1-5-21-1000', path: 'D:\\$Recycle.Bin\\S-1-5-21-1000', isDirectory: true }, - { name: 'S-1-5-21-1001', path: 'D:\\$Recycle.Bin\\S-1-5-21-1001', isDirectory: true } - ] - } - } - if (path === 'D:\\$Recycle.Bin\\S-1-5-21-1000') { - return { - entries: [ - { name: '$IABC123.pdf', path: 'D:\\$Recycle.Bin\\S-1-5-21-1000\\$IABC123.pdf', isDirectory: false, size: infoBytes.byteLength }, - { name: '$RABC123.pdf', path: 'D:\\$Recycle.Bin\\S-1-5-21-1000\\$RABC123.pdf', isDirectory: false, size: 20480 } - ] - } - } - if (path === 'D:\\$Recycle.Bin\\S-1-5-21-1001') { - return { success: false, errorCode: 'PERMISSION_DENIED', error: 'EACCES: 拒绝访问其他用户回收站目录' } - } - return { success: false, errorCode: 'FILE_NOT_FOUND', error: 'ENOENT' } - }, - filesystem_read_file: ({ path, encoding }) => { - assert.equal(encoding, 'base64') - assert.equal(path, 'D:\\$Recycle.Bin\\S-1-5-21-1000\\$IABC123.pdf') - return { content: toBase64(infoBytes) } - } - }) - - const snap = await dataRecovery.scanRecycleBinFast(host, ['D']) - assert.equal(snap.error, undefined) - assert.equal(snap.items.length, 1) - assert.equal(snap.items[0].name, '年度合作协议.pdf') - assert.equal(snap.items[0].originalPath, 'D:\\重要合同\\年度合作协议.pdf') - assert.equal(snap.items[0].sizeBytes, 20480) - assert.equal(snap.items[0].deletedAtMs, deletedMs) - assert.equal(snap.items[0].metadataStatus, 'parsed') - assert.deepEqual(snap.inaccessibleSids, ['D:\\$Recycle.Bin\\S-1-5-21-1001']) - assert.match(snap.permissionWarning, /管理员权限/) -}) - -test('data-recovery 安全硬拦截: 恢复目标盘符与源待恢复分区盘符相同时严格拒绝', async () => { - // 1. 直接校验函数测试 - const sameDriveCheck = dataRecovery.validateRecoveryOutputTarget('D:\\$Recycle.Bin\\S-1\\$R1.docx', 'd:\\Recovered') - assert.equal(sameDriveCheck.ok, false) - assert.equal(sameDriveCheck.errorCode, 'SAME_SOURCE_DRIVE') - assert.equal(sameDriveCheck.sourceDrive, 'D') - assert.equal(sameDriveCheck.targetDrive, 'D') - - const diffDriveCheck = dataRecovery.validateRecoveryOutputTarget('D:\\$Recycle.Bin\\S-1\\$R1.docx', 'E:\\Recovered') - assert.equal(diffDriveCheck.ok, true) - - // 2. 快速回收站恢复同盘拦截(严禁发起复制 IPC) - const host = createRealHostStub({ - filesystem_create_directory: () => ({ ok: true }), - filesystem_copy_file: () => { - throw new Error('同盘恢复必须在前置硬拦截,严禁写入源分区') - } - }) - const itemsOnC = [ - { - id: '1', - name: 'report.docx', - cachePath: 'C:\\$Recycle.Bin\\S-1-5-21-1000\\$R1.docx', - sourceDrive: 'C', - category: 'documents', - categoryName: '文档', - sizeBytes: 1024, - modifiedText: '', - metadataStatus: 'parsed' - } - ] - const sameDriveRes = await dataRecovery.restoreSelectedFiles(itemsOnC, 'C:\\Users\\Tester\\Desktop\\ZToolsRecovered', host) - assert.equal(sameDriveRes.ok, false) - assert.equal(sameDriveRes.restoredCount, 0) - assert.match(sameDriveRes.message, /源待恢复分区(C:\\)/) - assert.equal(host.calls.some((c) => c.channel === 'filesystem_copy_file'), false) - - // 3. 磁盘深度恢复同盘拦截(严禁发起 RecoverFile DLL 调用) - const deepHost = createRealHostStub({ - dllplugin_call_with_callback: () => { - throw new Error('同盘深度恢复必须在前置硬拦截') - } - }) - const deepBlocked = await dataRecovery.recoverDeepFiles( - { - taskId: 't_recover_1', - scanId: 'scan_001', - fileIds: ['101'], - targetPath: 'D:\\OutputFolder', - sourceDrives: ['C', 'D'] - }, - deepHost - ) - assert.equal(deepBlocked.ok, false) - assert.equal(deepBlocked.errorCode, 'SAME_SOURCE_DRIVE') - assert.equal(deepHost.calls.length, 0) -}) - -test('data-recovery 磁盘深度恢复: 完整验证 DataRecoveryPlugin 全部 12 个真实导出函数契约', async () => { - const invoked = [] - const host = createRealHostStub({ - dllplugin_call: ({ plugin, func, params }) => { - assert.equal(plugin, 'DataRecoveryPlugin') - invoked.push({ channel: 'dllplugin_call', func, params }) - switch (func) { - case 'GetDeviceList': - return { - success: true, - devices: [ - { - deviceId: '\\\\.\\PhysicalDrive0', - name: 'NVMe SSD 1TB', - size: 1000204886016, - type: 'SSD', - status: 'normal', - fileSystem: 'NTFS', - volumes: [{ letter: 'C' }, { letter: 'D' }] - } - ] - } - case 'GetPartitions': - return { - success: true, - partitions: [ - { - partitionNum: 0, - start: 2048, - length: 209715200, - description: 'NTFS Primary', - type: 'gpt', - fileSystem: 'ntfs', - allocated: true, - driveLetter: 'D' - } - ] - } - case 'StopScan': - return { success: true, message: 'Scan stopped' } - case 'EnumFiles': - return { - success: true, - totalCount: 1, - files: [ - { - fileId: '42', - id: 42, - name: 'photo.jpg', - path: '/Photos', - size: 409600, - type: 'image', - recoverable: true, - integrity: 'good', - isDeleted: true - } - ] - } - case 'GetFileMetadata': - return { - success: true, - name: 'photo.jpg', - path: '/Photos', - size: 409600, - type: 'image', - recoverable: true, - integrity: 'good', - isDeleted: true - } - case 'PreviewFile': - return { - success: true, - previewPath: 'C:\\ZTools\\Cache\\DataRecoveryPlugin\\preview_scan_001_42.jpg', - fileType: 'image' - } - case 'GetScanStatus': - return { - success: true, - scanning: true, - scanId: 'scan_001', - deviceId: '\\\\.\\PhysicalDrive0', - scanType: 'deep' - } - case 'GetScanHistory': - return { - success: true, - total: 1, - history: [ - { - scanId: 'scan_001', - deviceId: '\\\\.\\PhysicalDrive0', - deviceName: 'NVMe SSD 1TB', - partitionNum: 0, - scanType: 'deep', - scanScenario: 'deleted', - startTime: 1700000000, - endTime: 1700000120, - totalFiles: 128, - totalSize: 52428800, - status: 'completed', - description: '', - cacheAvailable: true - } - ] - } - default: - throw new Error(`unexpected sync func: ${func}`) - } - }, - dllplugin_call_with_callback: ({ plugin, func, params }) => { - assert.equal(plugin, 'DataRecoveryPlugin') - invoked.push({ channel: 'dllplugin_call_with_callback', func, params }) - if (func === 'GetDeviceListAsync') return { success: true, devices: [] } - if (func === 'StartScan') return { success: true, scanId: 'scan_001' } - if (func === 'EnumFilesAsync') return { success: true, files: [], totalCount: 0 } - if (func === 'RecoverFile') return { success: true, message: 'Recovery started' } - throw new Error(`unexpected callback func: ${func}`) - } - }) - - // 1. GetDeviceList - const devRes = await dataRecovery.getDeviceList(host) - assert.equal(devRes.ok, true) - assert.equal(devRes.data.length, 1) - assert.deepEqual(devRes.data[0].volumes, ['C', 'D']) - - // 2. GetDeviceListAsync - const devAsyncRes = await dataRecovery.getDeviceListAsync('task_dev_1', host) - assert.equal(devAsyncRes.ok, true) - - // 3. GetPartitions (允许 partitionNum === 0) - const partRes = await dataRecovery.getPartitions('\\\\.\\PhysicalDrive0', host) - assert.equal(partRes.ok, true) - assert.equal(partRes.data[0].partitionNum, 0) - assert.equal(partRes.data[0].driveLetter, 'D') - - // 4. StartScan (允许 partitionNum === 0) - const scanRes = await dataRecovery.startDiskScan( - { taskId: 'task_scan_1', deviceId: '\\\\.\\PhysicalDrive0', partitionNum: 0, scanType: 'deep' }, - host - ) - assert.equal(scanRes.ok, true) - assert.equal(scanRes.data.scanId, 'scan_001') - - // 5. GetScanStatus - const statusRes = await dataRecovery.getScanStatus('task_scan_1', host) - assert.equal(statusRes.ok, true) - assert.equal(statusRes.data.scanning, true) - - // 6. StopScan - const stopRes = await dataRecovery.stopDiskScan('task_scan_1', host) - assert.equal(stopRes.ok, true) - - // 7. EnumFiles - const enumRes = await dataRecovery.enumScanFiles({ scanId: 'scan_001', pageIndex: 0, pageSize: 50 }, host) - assert.equal(enumRes.ok, true) - assert.equal(enumRes.data.totalCount, 1) - assert.equal(enumRes.data.files[0].fileId, '42') - - // 8. EnumFilesAsync - const enumAsyncRes = await dataRecovery.enumScanFilesAsync({ taskId: 'task_enum_1', scanId: 'scan_001' }, host) - assert.equal(enumAsyncRes.ok, true) - - // 9. GetFileMetadata - const metaRes = await dataRecovery.getDeepFileMetadata('scan_001', '42', host) - assert.equal(metaRes.ok, true) - assert.equal(metaRes.data.name, 'photo.jpg') - - // 10. PreviewFile - const prevRes = await dataRecovery.previewDeepFile('scan_001', '42', host) - assert.equal(prevRes.ok, true) - assert.match(prevRes.data.previewPath, /preview_scan_001_42\.jpg$/) - - // 11. RecoverFile(跨盘 D -> E,允许通过) - const recRes = await dataRecovery.recoverDeepFiles( - { - taskId: 'task_rec_1', - scanId: 'scan_001', - fileIds: ['42'], - targetPath: 'E:\\ZToolsRecovered\\20261127', - sourceDrives: ['D'] - }, - host - ) - assert.equal(recRes.ok, true) - - // 12. GetScanHistory - const histRes = await dataRecovery.getScanHistory(10, host) - assert.equal(histRes.ok, true) - assert.equal(histRes.data[0].partitionNum, 0) - - // 确认全部 12 个真实方法都被完整覆盖调用 - const calledFuncs = new Set(invoked.map((x) => x.func)) - for (const fn of dataRecovery.DATA_RECOVERY_DLL_FUNCTIONS) { - assert.ok(calledFuncs.has(fn), `缺少对真实导出函数 ${fn} 的调用校验`) - } - assert.equal(calledFuncs.size, 12) -}) - -test('data-recovery: 不在客户端环境中运行不返回假数据,且双语热切换正常', async () => { - try { - setRuntimeLocale('zh-CN') - const snapZh = await dataRecovery.fetchRecoverableFiles() - assert.equal(snapZh.items.length, 0) - assert.match(snapZh.error, /客户端/) - - setRuntimeLocale('en-US') - const snapEn = await dataRecovery.fetchRecoverableFiles() - assert.equal(snapEn.items.length, 0) - assert.doesNotMatch(snapEn.error, /[\u4e00-\u9fa5]/) - const sameEn = dataRecovery.validateRecoveryOutputTarget('D:\\$Recycle.Bin\\S-1\\$R1', 'D:\\Recovered') - assert.equal(sameEn.ok, false) - assert.doesNotMatch(sameEn.error, /[\u4e00-\u9fa5]/) - } finally { - setRuntimeLocale('zh-CN') - } -}) diff --git a/extensions/data-recovery/tests/data-recovery.ui.test.mjs b/extensions/data-recovery/tests/data-recovery.ui.test.mjs deleted file mode 100644 index 93bd0b0..0000000 --- a/extensions/data-recovery/tests/data-recovery.ui.test.mjs +++ /dev/null @@ -1,128 +0,0 @@ -import test from 'node:test' -import assert from 'node:assert/strict' -import { createHost, mount } from '../../shared/test-harness.mjs' -import DataRecoveryCommand from '../dist/index.js' - -const FILETIME_EPOCH_DIFF_100NS = 116444736000000000n - -function buildRecycleInfoV2(originalPath, originalSize, deletedAtMs) { - const pathCharLen = originalPath.length + 1 - const buf = new Uint8Array(28 + pathCharLen * 2) - const view = new DataView(buf.buffer) - view.setBigUint64(0, 2n, true) - view.setBigUint64(8, BigInt(originalSize), true) - view.setBigUint64(16, BigInt(deletedAtMs) * 10000n + FILETIME_EPOCH_DIFF_100NS, true) - view.setUint32(24, pathCharLen, true) - for (let i = 0; i < originalPath.length; i += 1) { - view.setUint16(28 + i * 2, originalPath.charCodeAt(i), true) - } - return Buffer.from(buf).toString('base64') -} - -const DESKTOP_E = 'E:\\Users\\Tester\\Desktop' -const BIN_D = 'D:\\$Recycle.Bin\\S-1-5-21-1000' - -function installHost(host, desktopDir = DESKTOP_E) { - const copyCalls = [] - const infoA = buildRecycleInfoV2('D:\\Docs\\合同草案.docx', 2048, Date.UTC(2026, 4, 1, 9, 0, 0)) - const infoB = buildRecycleInfoV2('D:\\Pics\\封面图.png', 4096, Date.UTC(2026, 4, 2, 10, 0, 0)) - - host.ipc.system_get_path = async ({ name }) => (name === 'desktop' ? desktopDir : '') - host.ipc.system_get_disk_usage = async ({ drive }) => { - if (drive === 'D:\\') return { total: 1000, used: 400, available: 600 } - throw new Error('ENOENT') - } - host.ipc.filesystem_get_directory_contents = async ({ path }) => { - if (path === 'D:\\$Recycle.Bin') { - return { entries: [{ name: 'S-1-5-21-1000', path: BIN_D, isDirectory: true }] } - } - if (path === BIN_D) { - return { - entries: [ - { name: '$IAAA111.docx', path: `${BIN_D}\\$IAAA111.docx`, isDirectory: false, size: 128 }, - { name: '$RAAA111.docx', path: `${BIN_D}\\$RAAA111.docx`, isDirectory: false, size: 2048 }, - { name: '$IBBB222.png', path: `${BIN_D}\\$IBBB222.png`, isDirectory: false, size: 128 }, - { name: '$RBBB222.png', path: `${BIN_D}\\$RBBB222.png`, isDirectory: false, size: 4096 } - ] - } - } - return { success: false, errorCode: 'FILE_NOT_FOUND', error: 'ENOENT' } - } - host.ipc.filesystem_read_file = async ({ path }) => { - if (path.endsWith('$IAAA111.docx')) return { content: infoA } - if (path.endsWith('$IBBB222.png')) return { content: infoB } - return { success: false, error: 'FILE_NOT_FOUND' } - } - host.ipc.filesystem_create_directory = async () => ({ ok: true }) - host.ipc.filesystem_copy_file = async (params) => { - copyCalls.push(params) - return { ok: true } - } - host.ipc.dllplugin_call = async ({ plugin, func }) => { - assert.equal(plugin, 'DataRecoveryPlugin') - if (func === 'GetDeviceList') { - return { - success: true, - devices: [ - { - deviceId: '\\\\.\\PhysicalDrive0', - name: 'SSD 512GB', - size: 512000000000, - type: 'SSD', - status: 'normal', - volumes: [{ letter: 'D' }] - } - ] - } - } - return { success: true } - } - return copyCalls -} - -function fileRows(view) { - return view.items().filter((it) => String(it.props.id).startsWith('rec-item-')) -} - -test('data-recovery UI: 显示 $I 解析后的原始中文文件名与原路径,且默认不勾选', async () => { - const host = createHost() - const copyCalls = installHost(host) - const view = await mount(DataRecoveryCommand, host) - - const rows = fileRows(view) - assert.equal(rows.length, 2) - assert.ok(rows.every((r) => r.props.checked === false)) - assert.equal(rows[0].props.title, '合同草案.docx') - assert.match(rows[0].props.subtitle, /D:\\Docs\\合同草案\.docx/) - assert.equal(rows[1].props.title, '封面图.png') - - await view.run(rows[0], '恢复已勾选文件 (0 项)') - assert.equal(copyCalls.length, 0) - assert.equal(host.lastToast().title, '请先勾选要恢复的文件') - view.unmount() -}) - -test('data-recovery UI: 跨盘(D -> E)恢复成功使用原始文件名,同盘(D -> D)恢复被硬拦截', async () => { - const host = createHost() - const copyCalls = installHost(host, DESKTOP_E) - const view = await mount(DataRecoveryCommand, host) - - await view.run(fileRows(view)[1], '勾选此文件') - await view.run(fileRows(view)[0], '恢复已勾选文件 (1 项)') - assert.equal(copyCalls.length, 1) - assert.equal(copyCalls[0].sourcePath, `${BIN_D}\\$RBBB222.png`) - assert.match(copyCalls[0].destPath, /^E:\\Users\\Tester\\Desktop\\ZToolsRecovered\\\d{8}-\d{6}-\d{3}\\封面图\.png$/) - assert.equal(host.lastToast().style, 'SUCCESS') - view.unmount() - - // 同盘 D -> D 硬拦截测试 - const hostSame = createHost() - const copyCallsSame = installHost(hostSame, 'D:\\Users\\Tester\\Desktop') - const viewSame = await mount(DataRecoveryCommand, hostSame) - await viewSame.run(fileRows(viewSame)[0], '勾选此文件') - await viewSame.run(fileRows(viewSame)[0], '恢复已勾选文件 (1 项)') - assert.equal(copyCallsSame.length, 0) - assert.equal(hostSame.lastToast().style, 'FAILURE') - assert.match(hostSame.lastToast().message, /源待恢复分区(D:\\)/) - viewSame.unmount() -}) diff --git a/extensions/data-recovery/tsconfig.json b/extensions/data-recovery/tsconfig.json deleted file mode 100644 index 1346df8..0000000 --- a/extensions/data-recovery/tsconfig.json +++ /dev/null @@ -1,19 +0,0 @@ -{ - "compilerOptions": { - "target": "ES2022", - "module": "CommonJS", - "moduleResolution": "node", - "strict": true, - "esModuleInterop": true, - "skipLibCheck": true, - "forceConsistentCasingInFileNames": true, - "outDir": "dist", - "rootDir": "src", - "typeRoots": [ - "../../frontend/node_modules/@types" - ] - }, - "include": [ - "src/**/*" - ] -} diff --git a/extensions/wechat-multi/README.md b/extensions/wechat-multi/README.md deleted file mode 100644 index 86dc695..0000000 --- a/extensions/wechat-multi/README.md +++ /dev/null @@ -1,22 +0,0 @@ -# 微信多开 - -开发中,暂不在插件市场提供:客户端只会再运行一次微信程序,不能解除微信的单实例限制;微信已在运行时再启动通常只会切换到已有窗口,多开功能不成立。 - -再运行一次本机的微信电脑版程序,并列出正在运行的微信进程。 - -## 使用 - -- 命令:微信多开(插件主命令)。 -- 第一行"再运行一次微信":`Enter` 让客户端再运行一次微信程序。 -- 启动方式是在常见安装位置和注册表登记的安装目录中找到微信程序后直接再运行一次,不修改、不注入微信程序文件,也不会解除微信自身的单实例限制。界面提示"已再次运行微信程序"只表示程序已运行,是否多开成功以是否出现新的登录窗口为准。 -- 其余各行是正在运行的 WeChat / Weixin 进程,显示 PID、启动时间和内存占用;新版微信一个账号也会有多个同名进程,进程数不等于已登录的账号数。`Enter` 复制 PID。顶部状态条的"刷新"重新读取。 -- 未检测到微信安装路径、读取进程失败或启动失败时显示失败原因。不在 ZTools 客户端中运行时提示需要在客户端中使用,不显示示例数据。 - -## 平台与要求 - -- 支持:仅 Windows -- Windows 实现尚待真机复核。 - -## 网络与数据 - -- 不联网,数据只保存在本机。 diff --git a/extensions/wechat-multi/icon.svg b/extensions/wechat-multi/icon.svg deleted file mode 100644 index ad0e7be..0000000 --- a/extensions/wechat-multi/icon.svg +++ /dev/null @@ -1,3 +0,0 @@ - - - diff --git a/extensions/wechat-multi/package.json b/extensions/wechat-multi/package.json deleted file mode 100644 index 1d5a33a..0000000 --- a/extensions/wechat-multi/package.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "name": "@ztools/plugin-wechat-multi", - "version": "1.0.0", - "description": "列出正在运行的微信进程,并可再运行一次微信程序(不能解除微信的单实例限制)", - "main": "dist/index.js", - "types": "dist/index.d.ts", - "scripts": { - "build": "tsc", - "test": "node --test tests/*.test.mjs" - }, - "dependencies": { - "@ztools/declarative-ui": "workspace:*" - } -} diff --git a/extensions/wechat-multi/plugin.json b/extensions/wechat-multi/plugin.json deleted file mode 100644 index 1dee02c..0000000 --- a/extensions/wechat-multi/plugin.json +++ /dev/null @@ -1,58 +0,0 @@ -{ - "id": "wechat-multi", - "name": "微信多开", - "description": "基于本地白名单互斥体管理的 Windows 微信(3.x / 4.x)多开与账号实例管理助手。仅用于本地多实例辅助,不修改微信二进制,不承诺绕过微信协议或服务端限制", - "version": "2.1.0", - "author": "ZTools Team", - "entry": "dist/index.js", - "icon": "icon.svg", - "category": [ - "办公效率", - "系统工具" - ], - "categoryId": [ - "productivity", - "system" - ], - "permissions": [ - "system", - "child_process", - "clipboard" - ], - "requireAdmin": false, - "dllloader": "lib/WechatMultiPlugin.dll", - "minAppVersion": "1.3.0.0", - "nativeComponents": [ - { - "id": "wechat-multi-dll", - "kind": "dll", - "targetId": "windows-electron-any", - "arch": "ia32", - "abi": "ztools-native-host/v1", - "protocolVersion": 1, - "entry": "lib/WechatMultiPlugin.dll" - } - ], - "targets": [ - { - "id": "windows-electron-any", - "platform": "windows", - "runtime": "electron", - "arch": "x64" - } - ], - "defaultLocale": "zh-CN", - "i18n": { - "en-US": { - "name": "WeChat Multi-Instance", - "description": "Windows WeChat (3.x / 4.x) multi-instance and account manager using strict mutex whitelist handling. Does not modify WeChat binaries and does not guarantee bypassing WeChat protocol or server restrictions.", - "keywords": [ - "wechat", - "multi instance", - "launcher", - "process", - "weixin" - ] - } - } -} diff --git a/extensions/wechat-multi/src/error-i18n.ts b/extensions/wechat-multi/src/error-i18n.ts deleted file mode 100644 index d97366d..0000000 --- a/extensions/wechat-multi/src/error-i18n.ts +++ /dev/null @@ -1,213 +0,0 @@ -/** - * 声明式插件通用错误本地化解析器(R7 双轨平滑迁移共享底座)。 - * - * 规则: - * 1. 优先按结构化错误码(errorDetails.hostCode / details.hostCode / errorCode / code)查表: - * 先查插件传入的 codeMap,再查标准宿主错误码双语表; - * 2. 对称展示规则:中文模式(zh-CN)原文含 CJK 才直接展示,英文模式(en-US)原文不含 CJK 才直接展示, - * 既保留宿主精确本地化消息,又拦截英文技术原文裸露到中文界面、拦截中文原文裸露到英文界面; - * 3. 原文语言不匹配时优先使用标准宿主错误码译文,否则回退到插件本地 t(...) 兜底文案。 - */ - -import { getLocale } from '@ztools/declarative-ui' - -const CJK_REGEX = /[\u4e00-\u9fa5]/ - -const HOST_ERROR_CODE_MESSAGES: Record>> = { - 'zh-CN': { - INVALID_REQUEST: '请求参数无效', - METHOD_NOT_FOUND: '当前 ZTools 版本过低或不支持此接口,请升级客户端后重试', - METHOD_NOT_AVAILABLE: '当前 ZTools 版本过低或不支持此接口,请升级客户端后重试', - PERMISSION_DENIED: '权限不足,无法执行该操作', - REQUEST_TIMEOUT: '请求执行超时,请稍后重试', - CALLER_DESTROYED: '调用窗口已关闭,操作已中止', - APP_STOPPING: '应用正在退出,操作已取消', - CANCELLED: '操作已取消', - OPERATION_CANCELLED: '操作已取消', - NOT_SUPPORTED: '当前环境不支持此操作', - PLATFORM_NOT_SUPPORTED: '当前操作系统不支持此功能', - NETWORK_ERROR: '网络请求失败,请检查网络连接', - RESPONSE_TOO_LARGE: '响应数据超出大小限制', - FILE_ERROR: '文件操作失败', - FILE_NOT_FOUND: '目标文件或目录不存在', - FILE_TOO_LARGE: '文件大小超出限制', - FILE_ALREADY_EXISTS: '目标文件已存在', - DISK_FULL: '磁盘空间不足', - SHELL_ERROR: '系统命令或外部应用启动失败', - PROCESS_ERROR: '进程操作失败', - PROCESS_PROTECTED: '目标进程受系统保护,无法操作', - PROCESS_NOT_FOUND: '未找到目标进程', - PROCESS_ACCESS_DENIED: '无权访问或操作目标进程', - SCREEN_ERROR: '屏幕或窗口操作失败', - CLIPBOARD_ERROR: '剪贴板读写失败', - DATABASE_LOCKED: '本地数据库正被占用,请稍后重试', - DATABASE_KEY_NOT_FOUND: '未找到指定的数据项', - DATA_CORRUPT: '本地数据格式损坏或校验失败', - STORAGE_ERROR: '本地存储读写失败', - PLUGIN_BUSY: '插件正忙,请稍后重试', - PLUGIN_PERMISSION_REQUIRED: '插件缺少所需权限声明', - DLL_ERROR: '原生组件执行失败', - NATIVE_HOST_UNAVAILABLE: '原生宿主组件不可用', - NATIVE_HOST_ERROR: '原生宿主执行失败', - SERVICE_UNAVAILABLE: '系统提权服务不可用', - INTERNAL_ERROR: '宿主内部错误' - }, - 'en-US': { - INVALID_REQUEST: 'Invalid request parameters', - METHOD_NOT_FOUND: 'Your ZTools version is too old or does not support this API. Please upgrade and try again.', - METHOD_NOT_AVAILABLE: 'Your ZTools version is too old or does not support this API. Please upgrade and try again.', - PERMISSION_DENIED: 'Permission denied', - REQUEST_TIMEOUT: 'Request timed out. Please try again later.', - CALLER_DESTROYED: 'The caller window was closed and the operation was aborted', - APP_STOPPING: 'Application is exiting; operation cancelled', - CANCELLED: 'Operation cancelled', - OPERATION_CANCELLED: 'Operation cancelled', - NOT_SUPPORTED: 'This operation is not supported in the current environment', - PLATFORM_NOT_SUPPORTED: 'This feature is not supported on the current operating system', - NETWORK_ERROR: 'Network request failed. Please check your connection.', - RESPONSE_TOO_LARGE: 'Response payload exceeds size limit', - FILE_ERROR: 'File operation failed', - FILE_NOT_FOUND: 'Target file or directory not found', - FILE_TOO_LARGE: 'File size exceeds limit', - FILE_ALREADY_EXISTS: 'Target file already exists', - DISK_FULL: 'Insufficient disk space', - SHELL_ERROR: 'Failed to launch system command or external application', - PROCESS_ERROR: 'Process operation failed', - PROCESS_PROTECTED: 'Target process is protected by the system', - PROCESS_NOT_FOUND: 'Target process not found', - PROCESS_ACCESS_DENIED: 'Access denied for target process', - SCREEN_ERROR: 'Screen or window operation failed', - CLIPBOARD_ERROR: 'Failed to read or write clipboard', - DATABASE_LOCKED: 'Local database is locked. Please try again later.', - DATABASE_KEY_NOT_FOUND: 'Requested item was not found', - DATA_CORRUPT: 'Local data is corrupted or failed validation', - STORAGE_ERROR: 'Local storage operation failed', - PLUGIN_BUSY: 'Plugin is busy. Please try again later.', - PLUGIN_PERMISSION_REQUIRED: 'Plugin is missing required permission declaration', - DLL_ERROR: 'Native component execution failed', - NATIVE_HOST_UNAVAILABLE: 'Native host component is unavailable', - NATIVE_HOST_ERROR: 'Native host execution failed', - SERVICE_UNAVAILABLE: 'Elevated system service is unavailable', - INTERNAL_ERROR: 'Internal host error' - } -} - -function asObj(value: unknown): Record | null { - return value && typeof value === 'object' && !Array.isArray(value) - ? (value as Record) - : null -} - -function pickNonEmptyString(value: unknown): string { - return typeof value === 'string' && value.trim().length > 0 ? value.trim() : '' -} - -/** 从错误对象或宿主响应信封中提取结构化错误码(优先 errorCode,再 code) */ -export function extractErrorCode(source: unknown): string { - const rec = asObj(source) - if (!rec) return '' - const direct = pickNonEmptyString(rec.errorCode) || pickNonEmptyString(rec.code) - if (direct) return direct - const nestedErr = asObj(rec.error) - if (nestedErr) { - return pickNonEmptyString(nestedErr.errorCode) || pickNonEmptyString(nestedErr.code) - } - const nestedData = asObj(rec.data) - if (nestedData) { - return pickNonEmptyString(nestedData.errorCode) || pickNonEmptyString(nestedData.code) - } - return '' -} - -/** 从错误对象或宿主响应信封中提取 details.hostCode */ -export function extractHostCode(source: unknown): string { - const rec = asObj(source) - if (!rec) return '' - const directDetails = asObj(rec.errorDetails) || asObj(rec.details) - const fromDirect = directDetails ? pickNonEmptyString(directDetails.hostCode) : '' - if (fromDirect) return fromDirect - const nestedErr = asObj(rec.error) - if (nestedErr) { - const nestedDetails = asObj(nestedErr.errorDetails) || asObj(nestedErr.details) - const fromNested = nestedDetails ? pickNonEmptyString(nestedDetails.hostCode) : '' - if (fromNested) return fromNested - } - return '' -} - -/** 从错误对象、宿主响应或字符串中提取原始错误文案 */ -export function extractRawErrorText(source: unknown): string { - if (typeof source === 'string') return source.trim() - if (source instanceof Error) return source.message.trim() - const rec = asObj(source) - if (!rec) return '' - if ('error' in rec) { - if (typeof rec.error === 'string') return rec.error.trim() - const nestedErr = asObj(rec.error) - if (nestedErr) { - return pickNonEmptyString(nestedErr.message) || pickNonEmptyString(nestedErr.error) - } - return '' - } - return pickNonEmptyString(rec.message) -} - -/** 判断某段文本在当前 locale 下是否可直接展示给用户(对称规则:zh-CN 需含 CJK,en-US 需不含 CJK) */ -export function isDisplayableInCurrentLocale(text: string): boolean { - if (!text) return false - const locale = getLocale() - if (locale === 'zh-CN') return CJK_REGEX.test(text) - return !CJK_REGEX.test(text) -} - -/** - * 将宿主响应、异常对象或原始错误字符串安全解析为当前语言的提示文案: - * 1. 若对象属于成功响应且无 error,直接返回 fallback(避免误读成功态 message/code); - * 2. 优先按 hostCode / errorCode / code 查插件自定义 codeMap; - * 3. 若存在标准宿主错误码且无原文或原文语言不匹配,按当前语言查标准词典; - * 4. 若原始文案非空且符合当前语种(中文模式含 CJK,英文模式不含 CJK),保留原始文案; - * 5. 其余情况一律回退到插件本地传入的 fallback(即 t('...'))。 - */ -export function resolveErrorMessage( - source: unknown, - fallback: string, - codeMap?: Readonly> -): string { - if (source === null || source === undefined || source === '') { - return fallback - } - const rec = asObj(source) - if (rec && 'error' in rec && rec.ok === true && !rec.error) { - return fallback - } - - const hostCode = extractHostCode(source) - const code = extractErrorCode(source) - const rawText = extractRawErrorText(source) - - // 非失败响应容器若既无 error 文案也无 errorCode,直接返回 fallback(如 snapshot.error || t('empty')) - if (rec && 'error' in rec && !rawText && !rec.errorCode && rec.ok !== false && rec.success !== false) { - return fallback - } - - const locale = getLocale() - const dict = HOST_ERROR_CODE_MESSAGES[locale] ?? HOST_ERROR_CODE_MESSAGES['en-US'] - - if (codeMap) { - if (hostCode && codeMap[hostCode]) return codeMap[hostCode] - if (code && codeMap[code]) return codeMap[code] - } - - if (hostCode && dict[hostCode]) { - if (!rawText || !isDisplayableInCurrentLocale(rawText)) return dict[hostCode] - } - if (code && dict[code]) { - if (!rawText || !isDisplayableInCurrentLocale(rawText)) return dict[code] - } - - if (rawText && isDisplayableInCurrentLocale(rawText)) { - return rawText - } - - return fallback -} diff --git a/extensions/wechat-multi/src/i18n.ts b/extensions/wechat-multi/src/i18n.ts deleted file mode 100644 index ac03fcf..0000000 --- a/extensions/wechat-multi/src/i18n.ts +++ /dev/null @@ -1,121 +0,0 @@ -import { createTranslator } from "@ztools/declarative-ui"; - -const rawT = createTranslator( - { - "zh-CN": { - hostRequired: "需要在 ZTools 客户端中使用", - launchLimitNote: "风险提示:仅基于微信 3.x/4.x 已知互斥体白名单辅助本地多开,不修改微信程序,不承诺绕过微信协议或服务端限制;卸载本插件不会关闭您正在运行的微信", - defaultProcName: "微信", - errReadProcessesFailed: "读取微信状态失败", - errLaunchFailed: "启动微信失败", - errWeChatNotInstalled: "未检测到本地微信(WeChat.exe / Weixin.exe)安装路径,请先安装微信", - errUnsupportedVersion: "当前微信版本互斥体未在支持白名单内,为保护账号与进程安全已中止多开", - errElevatedProcess: "检测到运行中的微信以管理员权限启动,普通权限无法访问其句柄,请以普通权限启动微信后重试", - errNoNewProcess: "客户端没有返回新进程 PID,微信可能未启动", - errInvalidAccountIndex: "账号序号无效", - errDeleteAccountFailed: "删除账号记录失败", - errSetRemarkFailed: "设置账号备注失败", - errShowInstanceFailed: "激活微信窗口失败", - errSetCallbackFailed: "设置状态回调失败", - msgLaunchedAgain: "已启动新的微信实例 (PID {pid})", - msgAlreadyRunning: "该账号已在运行中 (PID {pid})", - msgInstanceActivated: "已激活微信窗口 (PID {pid})", - msgInstanceFound: "已定位运行中的微信实例 (PID {pid})", - msgAccountDeleted: "已删除账号记录", - msgRemarkUpdated: "已更新账号备注", - toastCopyFailed: "复制失败", - toastRefreshedTitle: "已刷新", - toastRefreshedMsg: "运行中的微信实例 {count} 个 · 已记录账号 {accounts} 个", - actionLaunchAgain: "启动新的微信实例", - actionLaunchAccount: "启动此账号", - actionShowInstance: "切换到此窗口", - actionDeleteAccount: "移除本地账号记录", - kwLaunch: "启动 多开", - launchMissingPathSub: "未检测到微信安装位置,请先安装 Windows 版微信", - actionRetryRead: "重新读取", - instanceStateStarting: "启动中", - instanceStateWaitingLogin: "待扫码登录", - instanceStateLoggedIn: "已登录", - instanceStateExited: "已退出", - instanceStateUnknown: "运行中", - instanceSubtitle: "PID {pid} · {state}", - accountSubtitleRunning: "运行中 · {wxid}", - accountSubtitleIdle: "未运行 · {wxid}", - actionCopyPid: "复制 PID", - toastCopiedPid: "已复制 PID", - navTitle: "微信多开", - searchPlaceholder: "搜索微信实例、账号备注、wxid 或 PID", - summaryFailed: "读取失败:{error}", - summaryNotInstalled: "未检测到本地微信安装 · 请先安装 Windows 版微信(3.x / 4.x)", - summaryRunning: "微信 {version} · 运行实例 {count} 个 · 已记录账号 {accounts} 个{warning}", - actionRefresh: "刷新", - sectionActions: "多开操作与风险提示", - sectionRunning: "正在运行的微信实例 ({count})", - sectionAccounts: "已记录微信账号 ({count})", - riskNoticeTitle: "使用风险与边界说明" - }, - "en-US": { - hostRequired: "Must be used inside ZTools client", - launchLimitNote: "Risk notice: Assists local multi-instance only via strict WeChat 3.x/4.x mutex whitelist without modifying binaries, and does not promise bypassing WeChat protocol or server limits. Uninstalling this plugin will never close running WeChat processes.", - defaultProcName: "WeChat", - errReadProcessesFailed: "Failed to read WeChat status", - errLaunchFailed: "Failed to launch WeChat", - errWeChatNotInstalled: "Local WeChat installation (WeChat.exe / Weixin.exe) not found. Please install WeChat first.", - errUnsupportedVersion: "Current WeChat version mutex is not in the supported whitelist; launch aborted to protect your account and process stability.", - errElevatedProcess: "Running WeChat process is elevated (Administrator); standard privileges cannot inspect its handles. Restart WeChat as standard user and retry.", - errNoNewProcess: "Client did not return a new process PID; WeChat may not have started", - errInvalidAccountIndex: "Invalid account index", - errDeleteAccountFailed: "Failed to delete account record", - errSetRemarkFailed: "Failed to update account remark", - errShowInstanceFailed: "Failed to activate WeChat window", - errSetCallbackFailed: "Failed to configure status callback", - msgLaunchedAgain: "Launched new WeChat instance (PID {pid})", - msgAlreadyRunning: "Account is already running (PID {pid})", - msgInstanceActivated: "Activated WeChat window (PID {pid})", - msgInstanceFound: "Located running WeChat instance (PID {pid})", - msgAccountDeleted: "Account record removed", - msgRemarkUpdated: "Account remark updated", - toastCopyFailed: "Copy failed", - toastRefreshedTitle: "Refreshed", - toastRefreshedMsg: "{count} running [[count:instance|instances]] · {accounts} saved [[accounts:account|accounts]]", - actionLaunchAgain: "Launch New WeChat Instance", - actionLaunchAccount: "Launch This Account", - actionShowInstance: "Activate Window", - actionDeleteAccount: "Remove Saved Record", - kwLaunch: "launch multi open", - launchMissingPathSub: "WeChat installation not detected; install WeChat for Windows first", - actionRetryRead: "Retry", - instanceStateStarting: "Starting", - instanceStateWaitingLogin: "Waiting Login", - instanceStateLoggedIn: "Logged In", - instanceStateExited: "Exited", - instanceStateUnknown: "Running", - instanceSubtitle: "PID {pid} · {state}", - accountSubtitleRunning: "Running · {wxid}", - accountSubtitleIdle: "Idle · {wxid}", - actionCopyPid: "Copy PID", - toastCopiedPid: "PID copied", - navTitle: "WeChat Multi-Instance", - searchPlaceholder: "Search WeChat instances, account remarks, wxid, or PID", - summaryFailed: "Read failed: {error}", - summaryNotInstalled: "WeChat not installed locally · Install WeChat for Windows (3.x / 4.x) first", - summaryRunning: "WeChat {version} · {count} running · {accounts} saved{warning}", - actionRefresh: "Refresh", - sectionActions: "Multi-Instance Actions & Risk Notice", - sectionRunning: "Running WeChat Instances ({count})", - sectionAccounts: "Saved WeChat Accounts ({count})", - riskNoticeTitle: "Usage Risks & Boundaries" - } - }, - { defaultLocale: "en-US" } -); - -export const t: typeof rawT = (key, params) => { - const out = rawT(key, params); - if (!out.includes("[[")) return out; - return out.replace(/\[\[([A-Za-z0-9_.-]+):([^|\]]+)\|([^\]]+)\]\]/g, (_m, k: string, one: string, other: string) => { - const v = params?.[k]; - const n = typeof v === "number" ? v : Number(String(v ?? "").replace(/,/g, "")); - return n === 1 ? one : other; - }); -}; diff --git a/extensions/wechat-multi/src/index.ts b/extensions/wechat-multi/src/index.ts deleted file mode 100644 index 91ca449..0000000 --- a/extensions/wechat-multi/src/index.ts +++ /dev/null @@ -1,277 +0,0 @@ -import { - List, - ActionPanel, - Action, - Icon, - Clipboard, - useLocale, - useState, - useEffect, - showToast, - Toast -} from "@ztools/declarative-ui"; -import { - type WechatAccountItem, - type WechatInstanceItem, - deleteWeChatAccount, - fetchWechatInstances, - filterWechatInstances, - formatBytes, - formatInstanceState, - launchWeChat, - showWeChatInstance -} from "./logic.js"; -import { t } from "./i18n.js"; -import { resolveErrorMessage } from "./error-i18n.js"; - -export * from "./logic.js"; - -async function copyWithToast(text: string, successTitle: string): Promise { - try { - await Clipboard.copy(text); - } catch (err) { - await showToast({ - style: Toast.Style.Failure, - title: t("toastCopyFailed"), - message: err instanceof Error ? err.message : String(err) - }); - return; - } - await showToast({ style: Toast.Style.Success, title: successTitle, message: text }); -} - -export function WechatMultiCommand() { - useLocale(); - const [searchText, setSearchText] = useState(""); - const [instances, setInstances] = useState([]); - const [accounts, setAccounts] = useState([]); - const [installed, setInstalled] = useState(false); - const [installPath, setInstallPath] = useState(""); - const [versionName, setVersionName] = useState(""); - const [loadError, setLoadError] = useState(""); - const [warning, setWarning] = useState(""); - const [isLoading, setIsLoading] = useState(true); - - async function refreshInstances(showNotice = false) { - setIsLoading(true); - try { - const snap = await fetchWechatInstances(); - setInstances(snap.instances); - setAccounts(snap.accounts); - setInstalled(snap.installed); - setInstallPath(snap.installPath); - setVersionName(snap.versionName); - setLoadError(snap.ok ? "" : resolveErrorMessage(snap, t("errReadProcessesFailed"))); - setWarning(snap.warning || ""); - if (!snap.ok) { - if (showNotice) { - await showToast({ - style: Toast.Style.Failure, - title: t("errReadProcessesFailed"), - message: snap.error - }); - } - } else if (showNotice) { - await showToast({ - style: Toast.Style.Success, - title: t("toastRefreshedTitle"), - message: t("toastRefreshedMsg", { count: snap.instances.length, accounts: snap.accounts.length }) - }); - } - } finally { - setIsLoading(false); - } - } - - useEffect(() => { - void refreshInstances(false); - }, []); - - async function handleLaunch(wxid = "") { - if (!installed && !installPath) { - await showToast({ - style: Toast.Style.Failure, - title: t("errLaunchFailed"), - message: t("errWeChatNotInstalled") - }); - return; - } - const res = await launchWeChat(wxid); - if (!res.ok) { - await showToast({ style: Toast.Style.Failure, title: t("errLaunchFailed"), message: res.message }); - return; - } - if (res.action === "already_running" && res.pid > 0) { - await showWeChatInstance(res.pid); - } - await showToast({ style: Toast.Style.Success, title: res.message, message: t("launchLimitNote") }); - await refreshInstances(false); - } - - async function handleShowInstance(pid: number) { - const res = await showWeChatInstance(pid); - await showToast({ - style: res.ok ? Toast.Style.Success : Toast.Style.Failure, - title: res.ok ? res.message : t("errShowInstanceFailed"), - message: res.ok ? "" : res.message - }); - } - - async function handleDeleteAccount(acc: WechatAccountItem) { - const res = await deleteWeChatAccount({ accountIndex: acc.index, wxid: acc.wxid }); - await showToast({ - style: res.ok ? Toast.Style.Success : Toast.Style.Failure, - title: res.ok ? res.message : t("errDeleteAccountFailed"), - message: res.ok ? acc.wxid : res.message - }); - if (res.ok) { - await refreshInstances(false); - } - } - - const filteredInstances = filterWechatInstances(instances, searchText); - const query = searchText.trim().toLowerCase(); - const filteredAccounts = query - ? accounts.filter( - (acc) => - acc.remark.toLowerCase().includes(query) || - acc.nickname.toLowerCase().includes(query) || - acc.wxid.toLowerCase().includes(query) - ) - : accounts; - - const launchTitle = t("actionLaunchAgain"); - const showLaunchRow = - !loadError && - (!query || - launchTitle.toLowerCase().includes(query) || - t("kwLaunch").toLowerCase().includes(query)); - - const launchRow = List.Item({ - id: "wx-launch", - title: launchTitle, - subtitle: installed && installPath ? `${installPath} · ${t("launchLimitNote")}` : t("launchMissingPathSub"), - icon: Icon.Plus, - actions: ActionPanel({ - title: launchTitle, - children: [Action({ title: launchTitle, icon: Icon.Plus, onAction: () => handleLaunch("") })] - }) - }); - - const statusRow = List.Item({ - id: "wx-status", - title: t("errReadProcessesFailed"), - subtitle: loadError, - icon: Icon.ExclamationMark, - actions: ActionPanel({ - title: t("errReadProcessesFailed"), - children: [Action({ title: t("actionRetryRead"), icon: Icon.ArrowClockwise, onAction: () => refreshInstances(true) })] - }) - }); - - const instanceRows = filteredInstances.map((item) => - List.Item({ - id: item.id, - title: item.displayName, - subtitle: t("instanceSubtitle", { pid: item.pid, state: formatInstanceState(item.state) }), - icon: Icon.AppWindow, - accessories: [ - ...(item.wxid ? [{ tag: { value: item.wxid } }] : []), - ...(item.memoryBytes > 0 ? [{ text: formatBytes(item.memoryBytes) }] : []) - ], - actions: ActionPanel({ - title: `${item.displayName} (PID ${item.pid})`, - children: [ - Action({ - title: t("actionShowInstance"), - icon: Icon.AppWindow, - onAction: () => handleShowInstance(item.pid) - }), - Action({ - title: t("actionCopyPid"), - icon: Icon.Clipboard, - onAction: () => copyWithToast(String(item.pid), t("toastCopiedPid")) - }) - ] - }) - }) - ); - - const accountRows = filteredAccounts.map((acc) => { - const title = acc.remark || acc.nickname || acc.wxid || `${t("defaultProcName")} #${acc.index}`; - return List.Item({ - id: `wx-acc-${acc.index}`, - title, - subtitle: acc.running - ? t("accountSubtitleRunning", { wxid: acc.wxid }) - : t("accountSubtitleIdle", { wxid: acc.wxid }), - icon: Icon.Person, - actions: ActionPanel({ - title, - children: [ - Action({ - title: t("actionLaunchAccount"), - icon: Icon.Plus, - onAction: () => handleLaunch(acc.wxid) - }), - Action({ - title: t("actionDeleteAccount"), - icon: Icon.Trash, - onAction: () => handleDeleteAccount(acc) - }) - ] - }) - }); - }); - - const summaryText = loadError - ? t("summaryFailed", { error: loadError }) - : !installed - ? t("summaryNotInstalled") - : t("summaryRunning", { - version: versionName || "3.x/4.x", - count: instances.length, - accounts: accounts.length, - warning: warning ? ` · ${warning}` : "" - }); - - return List({ - navigationTitle: t("navTitle"), - searchBarPlaceholder: t("searchPlaceholder"), - onSearchTextChange: setSearchText, - isShowingDetail: false, - isLoading, - filterBar: { - summaryText, - actions: [ - { - id: "refresh-wx", - label: t("actionRefresh"), - title: t("actionRefresh"), - style: "secondary", - onAction: () => void refreshInstances(true) - } - ] - }, - children: [ - List.Section({ - title: t("sectionActions"), - children: loadError ? [statusRow] : showLaunchRow ? [launchRow] : [] - }), - List.Section({ - title: t("sectionRunning", { count: filteredInstances.length }), - children: instanceRows - }), - ...(accountRows.length > 0 - ? [ - List.Section({ - title: t("sectionAccounts", { count: filteredAccounts.length }), - children: accountRows - }) - ] - : []) - ] - }); -} - -export default WechatMultiCommand; diff --git a/extensions/wechat-multi/src/logic.ts b/extensions/wechat-multi/src/logic.ts deleted file mode 100644 index cc89bbc..0000000 --- a/extensions/wechat-multi/src/logic.ts +++ /dev/null @@ -1,478 +0,0 @@ -/** - * 微信多开业务逻辑层 —— 全面对齐 WeChatMultiPlugin.dll 真实导出的 8 个 C++ 接口: - * - IsWeChatInstalled - * - GetAccounts - * - GetInstances - * - LaunchWeChat - * - SetCallback - * - DeleteAccount - * - SetAccountRemark - * - ShowInstance - * - * 安全与边界声明: - * - 仅依赖同用户权限的白名单互斥体机制(requireAdmin: false),不注入/修改微信二进制; - * - 遇到未在白名单内的未知微信版本或未安装微信时如实返回结构化错误,不盲目强启; - * - 绝不提供终止用户微信进程的能力。 - */ - -import { invokePluginService, isRealElectronHost, formatBytes } from "./native-ipc.js"; -import { t } from "./i18n.js"; -import { extractErrorCode, resolveErrorMessage } from "./error-i18n.js"; - -type DynamicBridge = ReturnType; - -export { formatBytes }; - -export const DLL_PLUGIN_NAME = "WeChatMultiPlugin"; - -/** WeChatMultiPlugin.dll 真实导出的全部 8 个业务函数白名单 */ -export const WECHAT_MULTI_DLL_FUNCTIONS = [ - "LaunchWeChat", - "GetAccounts", - "GetInstances", - "SetCallback", - "DeleteAccount", - "SetAccountRemark", - "IsWeChatInstalled", - "ShowInstance" -] as const; - -export type WeChatDllFunctionName = (typeof WECHAT_MULTI_DLL_FUNCTIONS)[number]; - -export function getHostRequiredMessage(): string { - return t("hostRequired"); -} - -export function getLaunchLimitNote(): string { - return t("launchLimitNote"); -} - -export type WeChatInstanceState = "starting" | "waiting_login" | "logged_in" | "exited" | "unknown"; - -export interface WechatInstallInfo { - ok: boolean; - installed: boolean; - path: string; - version: number; - versionName: string; - error?: string; - errorCode?: string; -} - -export interface WechatAccountItem { - index: number; - wxid: string; - nickname: string; - remark: string; - avatarPath: string; - running: boolean; -} - -export interface WechatInstanceItem { - id: string; - pid: number; - name: string; - wxid: string; - state: WeChatInstanceState; - displayName: string; - remark: string; - nickname: string; - avatarPath: string; - memoryBytes: number; - startTime: string; -} - -export interface WechatMultiSnapshot { - ok: boolean; - error?: string; - warning?: string; - installed: boolean; - installPath: string; - version: number; - versionName: string; - instances: WechatInstanceItem[]; - accounts: WechatAccountItem[]; -} - -export interface WechatLaunchResult { - ok: boolean; - action?: "launched" | "already_running"; - pid: number; - pids: number[]; - executablePath: string; - message: string; - errorCode?: string; -} - -export interface WechatActionResult { - ok: boolean; - message: string; - activated?: boolean; - pid?: number; - errorCode?: string; -} - -function hostAvailable(hostOverride?: DynamicBridge): boolean { - return Boolean(hostOverride) || isRealElectronHost(hostOverride); -} - -function normalizeState(raw: unknown): WeChatInstanceState { - switch (String(raw || "").toLowerCase()) { - case "starting": - return "starting"; - case "waiting_login": - return "waiting_login"; - case "logged_in": - return "logged_in"; - case "exited": - return "exited"; - default: - return "unknown"; - } -} - -export function formatInstanceState(state: WeChatInstanceState): string { - switch (state) { - case "starting": - return t("instanceStateStarting"); - case "waiting_login": - return t("instanceStateWaitingLogin"); - case "logged_in": - return t("instanceStateLoggedIn"); - case "exited": - return t("instanceStateExited"); - default: - return t("instanceStateUnknown"); - } -} - -function toInstance(raw: DynamicBridge): WechatInstanceItem | null { - if (!raw || typeof raw !== "object") return null; - const pid = Number(raw.pid); - if (!Number.isInteger(pid) || pid <= 0) return null; - const displayName = String(raw.displayName || raw.remark || raw.nickname || raw.name || t("defaultProcName")); - const memoryBytes = Number(raw.workingSetBytes ?? raw.memoryBytes ?? 0); - return { - id: `wx-proc-${pid}`, - pid, - name: displayName, - displayName, - wxid: String(raw.wxid || ""), - state: normalizeState(raw.state), - remark: String(raw.remark || ""), - nickname: String(raw.nickname || ""), - avatarPath: String(raw.avatarPath || ""), - memoryBytes: Number.isFinite(memoryBytes) && memoryBytes > 0 ? memoryBytes : 0, - startTime: typeof raw.startTime === "string" ? raw.startTime : "" - }; -} - -function toAccount(raw: DynamicBridge): WechatAccountItem | null { - if (!raw || typeof raw !== "object") return null; - const index = Number(raw.index); - if (!Number.isInteger(index) || index < 0) return null; - return { - index, - wxid: String(raw.wxid || ""), - nickname: String(raw.nickname || ""), - remark: String(raw.remark || ""), - avatarPath: String(raw.avatarPath || ""), - running: Boolean(raw.running) - }; -} - -function mapLaunchErrorMessage(data: DynamicBridge, fallbackRes: DynamicBridge): { message: string; errorCode?: string } { - const code = extractErrorCode(data) || extractErrorCode(fallbackRes); - const rawErr = String(data?.error || fallbackRes?.error || ""); - if ( - code === "UNSUPPORTED_OPTION" || - code === "UNSUPPORTED_WECHAT_VERSION" || - data?.launchErrorCode === -8 || - /unsupported\s*wechat\s*version|whitelist/i.test(rawErr) - ) { - return { message: t("errUnsupportedVersion"), errorCode: "UNSUPPORTED_WECHAT_VERSION" }; - } - if ( - code === "FILE_NOT_FOUND" || - code === "WECHAT_NOT_FOUND" || - data?.launchErrorCode === -1 || - /not\s*installed|installation\s*not\s*found/i.test(rawErr) - ) { - return { message: t("errWeChatNotInstalled"), errorCode: "WECHAT_NOT_FOUND" }; - } - if ( - code === "PERMISSION_DENIED" || - data?.launchErrorCode === -9 || - /elevated\s*wechat|access\s*denied/i.test(rawErr) - ) { - return { message: t("errElevatedProcess"), errorCode: "PERMISSION_DENIED" }; - } - return { - message: resolveErrorMessage(data && typeof data === "object" && data.error ? data : fallbackRes, t("errLaunchFailed")), - ...(code ? { errorCode: code } : {}) - }; -} - -/** 1/8: IsWeChatInstalled — 检测本机是否安装微信及版本/路径 */ -export async function checkWeChatInstalled(hostOverride?: DynamicBridge): Promise { - if (!hostAvailable(hostOverride)) { - return { ok: false, installed: false, path: "", version: 0, versionName: "", error: t("hostRequired") }; - } - const res = await invokePluginService(DLL_PLUGIN_NAME, "IsWeChatInstalled", {}, hostOverride); - const data = res.data; - if (!res.ok || !data || typeof data !== "object" || data.success === false || data.ok === false) { - const errSource = data && typeof data === "object" && data.error ? data : res; - return { - ok: false, - installed: false, - path: "", - version: 0, - versionName: "", - error: resolveErrorMessage(errSource, t("errReadProcessesFailed")), - ...(extractErrorCode(errSource) ? { errorCode: extractErrorCode(errSource) } : {}) - }; - } - return { - ok: true, - installed: Boolean(data.installed), - path: String(data.path || ""), - version: typeof data.version === "number" && Number.isFinite(data.version) ? data.version : 0, - versionName: String(data.versionName || "") - }; -} - -/** 2/8: GetAccounts — 读取已保存的微信账号列表 */ -export async function getWeChatAccounts( - hostOverride?: DynamicBridge -): Promise<{ ok: boolean; accounts: WechatAccountItem[]; error?: string }> { - if (!hostAvailable(hostOverride)) { - return { ok: false, accounts: [], error: t("hostRequired") }; - } - const res = await invokePluginService(DLL_PLUGIN_NAME, "GetAccounts", {}, hostOverride); - const data = res.data; - if (!res.ok || !data || typeof data !== "object" || data.success === false || data.ok === false) { - const errSource = data && typeof data === "object" && data.error ? data : res; - return { ok: false, accounts: [], error: resolveErrorMessage(errSource, t("errReadProcessesFailed")) }; - } - const rawList = Array.isArray(data.accounts) ? data.accounts : []; - const accounts = rawList - .map(toAccount) - .filter((item: WechatAccountItem | null): item is WechatAccountItem => item !== null); - return { ok: true, accounts }; -} - -/** 3/8: GetInstances — 读取当前受监控的运行中微信实例列表 */ -export async function getWeChatInstances( - hostOverride?: DynamicBridge -): Promise<{ ok: boolean; instances: WechatInstanceItem[]; error?: string }> { - if (!hostAvailable(hostOverride)) { - return { ok: false, instances: [], error: t("hostRequired") }; - } - const res = await invokePluginService(DLL_PLUGIN_NAME, "GetInstances", {}, hostOverride); - const data = res.data; - if (!res.ok || !data || typeof data !== "object" || data.success === false || data.ok === false) { - const errSource = data && typeof data === "object" && data.error ? data : res; - return { ok: false, instances: [], error: resolveErrorMessage(errSource, t("errReadProcessesFailed")) }; - } - const rawList = Array.isArray(data.instances) ? data.instances : []; - const instances = rawList - .map(toInstance) - .filter((item: WechatInstanceItem | null): item is WechatInstanceItem => item !== null); - return { ok: true, instances }; -} - -/** 4/8: LaunchWeChat — 启动新微信实例或指定 wxid 账号(已运行时返回 already_running) */ -export async function launchWeChat(wxid = "", hostOverride?: DynamicBridge): Promise { - if (!hostAvailable(hostOverride)) { - return { ok: false, pid: 0, pids: [], executablePath: "", message: t("hostRequired") }; - } - const res = await invokePluginService(DLL_PLUGIN_NAME, "LaunchWeChat", { wxid }, hostOverride); - const data = res.data; - if (!res.ok || !data || typeof data !== "object" || data.ok === false || data.success === false) { - const mapped = mapLaunchErrorMessage(data, res); - return { - ok: false, - pid: 0, - pids: [], - executablePath: "", - message: mapped.message, - ...(mapped.errorCode ? { errorCode: mapped.errorCode } : {}) - }; - } - const pid = Number(data.pid ?? 0); - if (!Number.isInteger(pid) || pid <= 0) { - return { ok: false, pid: 0, pids: [], executablePath: "", message: t("errNoNewProcess") }; - } - const action = data.action === "already_running" ? "already_running" : "launched"; - return { - ok: true, - action, - pid, - pids: [pid], - executablePath: String(data.path || data.wechatPath || ""), - message: action === "already_running" ? t("msgAlreadyRunning", { pid }) : t("msgLaunchedAgain", { pid }) - }; -} - -/** 5/8: SetCallback — 配置原生插件状态回调模式 */ -export async function setWeChatCallback( - params: Record = {}, - hostOverride?: DynamicBridge -): Promise { - if (!hostAvailable(hostOverride)) { - return { ok: false, message: t("hostRequired") }; - } - const res = await invokePluginService(DLL_PLUGIN_NAME, "SetCallback", params, hostOverride); - const data = res.data; - if (!res.ok || !data || typeof data !== "object" || data.success === false || data.ok === false) { - const errSource = data && typeof data === "object" && data.error ? data : res; - return { ok: false, message: resolveErrorMessage(errSource, t("errSetCallbackFailed")) }; - } - return { ok: true, message: String(data.message || "OK") }; -} - -/** 6/8: DeleteAccount — 删除已保存的本地账号记录(支持 accountIndex 或 wxid) */ -export async function deleteWeChatAccount( - target: { accountIndex?: number; wxid?: string }, - hostOverride?: DynamicBridge -): Promise { - if (!hostAvailable(hostOverride)) { - return { ok: false, message: t("hostRequired") }; - } - const params: Record = {}; - if (typeof target.accountIndex === "number" && Number.isInteger(target.accountIndex) && target.accountIndex > 0) { - params.accountIndex = target.accountIndex; - } - if (typeof target.wxid === "string" && target.wxid.trim()) { - params.wxid = target.wxid.trim(); - } - if (Object.keys(params).length === 0) { - return { ok: false, message: t("errInvalidAccountIndex"), errorCode: "INVALID_PARAMS" }; - } - const res = await invokePluginService(DLL_PLUGIN_NAME, "DeleteAccount", params, hostOverride); - const data = res.data; - if (!res.ok || !data || typeof data !== "object" || data.success === false || data.ok === false) { - const errSource = data && typeof data === "object" && data.error ? data : res; - return { ok: false, message: resolveErrorMessage(errSource, t("errDeleteAccountFailed")) }; - } - return { ok: true, message: t("msgAccountDeleted") }; -} - -/** 7/8: SetAccountRemark — 修改已保存账号的本地备注名 */ -export async function setWeChatAccountRemark( - accountIndex: number, - remark: string, - hostOverride?: DynamicBridge -): Promise { - if (!hostAvailable(hostOverride)) { - return { ok: false, message: t("hostRequired") }; - } - if (!Number.isInteger(accountIndex) || accountIndex <= 0) { - return { ok: false, message: t("errInvalidAccountIndex"), errorCode: "INVALID_PARAM_RANGE" }; - } - const res = await invokePluginService( - DLL_PLUGIN_NAME, - "SetAccountRemark", - { accountIndex, remark: String(remark ?? "") }, - hostOverride - ); - const data = res.data; - if (!res.ok || !data || typeof data !== "object" || data.success === false || data.ok === false) { - const errSource = data && typeof data === "object" && data.error ? data : res; - return { ok: false, message: resolveErrorMessage(errSource, t("errSetRemarkFailed")) }; - } - return { ok: true, message: t("msgRemarkUpdated") }; -} - -/** 8/8: ShowInstance — 定位并激活指定 PID 的微信窗口 */ -export async function showWeChatInstance(pid: number, hostOverride?: DynamicBridge): Promise { - if (!hostAvailable(hostOverride)) { - return { ok: false, message: t("hostRequired") }; - } - if (!Number.isInteger(pid) || pid <= 0) { - return { ok: false, message: t("errShowInstanceFailed"), errorCode: "INVALID_PARAMS" }; - } - const res = await invokePluginService(DLL_PLUGIN_NAME, "ShowInstance", { pid }, hostOverride); - const data = res.data; - if (!res.ok || !data || typeof data !== "object" || data.success === false || data.ok === false) { - const errSource = data && typeof data === "object" && data.error ? data : res; - return { - ok: false, - message: resolveErrorMessage(errSource, t("errShowInstanceFailed")), - ...(extractErrorCode(errSource) ? { errorCode: extractErrorCode(errSource) } : {}) - }; - } - const activated = Boolean(data.activated); - return { - ok: true, - pid, - activated, - message: activated ? t("msgInstanceActivated", { pid }) : t("msgInstanceFound", { pid }) - }; -} - -/** - * 聚合拉取微信安装状态、运行中实例与已保存账号(全部走真实 C++ 导出接口)。 - */ -export async function fetchWechatInstances(hostOverride?: DynamicBridge): Promise { - const empty: WechatMultiSnapshot = { - ok: false, - installed: false, - installPath: "", - version: 0, - versionName: "", - instances: [], - accounts: [] - }; - if (!hostAvailable(hostOverride)) { - return { ...empty, error: t("hostRequired") }; - } - - const [installInfo, instancesRes, accountsRes] = await Promise.all([ - checkWeChatInstalled(hostOverride), - getWeChatInstances(hostOverride), - getWeChatAccounts(hostOverride) - ]); - - if (!installInfo.ok && !instancesRes.ok) { - return { - ...empty, - error: installInfo.error || instancesRes.error || t("errReadProcessesFailed") - }; - } - - const warnings: string[] = []; - if (!installInfo.ok && installInfo.error) warnings.push(installInfo.error); - if (!instancesRes.ok && instancesRes.error) warnings.push(instancesRes.error); - if (!accountsRes.ok && accountsRes.error) warnings.push(accountsRes.error); - - return { - ok: true, - ...(warnings.length > 0 ? { warning: warnings.join(" · ") } : {}), - installed: installInfo.installed, - installPath: installInfo.path, - version: installInfo.version, - versionName: installInfo.versionName, - instances: instancesRes.ok ? instancesRes.instances : [], - accounts: accountsRes.ok ? accountsRes.accounts : [] - }; -} - -export const fetchWeChatMultiSnapshot = fetchWechatInstances; - -export async function launchWechatAgain(hostOverride?: DynamicBridge): Promise { - return launchWeChat("", hostOverride); -} - -export function filterWechatInstances(items: WechatInstanceItem[], query: string): WechatInstanceItem[] { - if (!Array.isArray(items)) return []; - const q = typeof query === "string" ? query.trim().toLowerCase() : ""; - if (!q) return items; - return items.filter( - (i) => - i.name.toLowerCase().includes(q) || - i.wxid.toLowerCase().includes(q) || - i.remark.toLowerCase().includes(q) || - String(i.pid).includes(q) - ); -} diff --git a/extensions/wechat-multi/src/native-ipc.ts b/extensions/wechat-multi/src/native-ipc.ts deleted file mode 100644 index 1364327..0000000 --- a/extensions/wechat-multi/src/native-ipc.ts +++ /dev/null @@ -1,1902 +0,0 @@ -import { getLocale } from '@ztools/declarative-ui' - -type DynamicBridge = ReturnType - -const NATIVE_IPC_MESSAGES: Record string - dirEntrySep: string - dirErrorColon: string - deepScanUnavailable: string - pathEmpty: string - invalidMethodEmpty: string - invalidMethodFormat: string - invalidParamsObject: string - paramTooLong: (key: string) => string - paramOutOfRange: (key: string) => string - methodParamEmpty: string - invalidMethodType: string - malformedDllResponse: string - unknownDllError: string - hostIpcFailed: (pluginName: string, method: string) => string - hostUnavailable: (pluginName: string, method: string) => string - callFailed: string - movedToTrash: string - deleteFailed: string - revealedInFolder: string - revealFailed: string - opened: string - openFailed: string - pluginCallNotReady: string -}> = { - 'zh-CN': { - ipcCallFailed: 'IPC 调用返回失败', - ipcInnerFailed: 'IPC 内部调用失败', - scanIncomplete: '扫描结果不完整', - dirReadFailed: (details, moreCount) => - `目录读取失败或不完整:${details}${moreCount > 0 ? `;另有 ${moreCount} 个目录` : ''}`, - dirEntrySep: ';', - dirErrorColon: ':', - deepScanUnavailable: '深度扫描不可用,仅列出一级目录,结果不完整', - pathEmpty: '路径不能为空', - invalidMethodEmpty: 'INVALID_METHOD: 调用方法名不能为空', - invalidMethodFormat: 'INVALID_METHOD_FORMAT: 方法名包含非法字符或超长', - invalidParamsObject: 'INVALID_PARAMS: 参数必须为非空对象', - paramTooLong: (key) => `PARAM_TOO_LONG: 参数 ${key} 超过最大长度限制`, - paramOutOfRange: (key) => `PARAM_OUT_OF_RANGE: 数值参数 ${key} 越界或非有限数`, - methodParamEmpty: 'method 参数不能为空', - invalidMethodType: 'INVALID_METHOD: method 不能为空且必须为字符串', - malformedDllResponse: 'MALFORMED_DLL_RESPONSE: 原生组件返回了损坏的 JSON 数据', - unknownDllError: '原生组件返回未知错误', - hostIpcFailed: (pluginName, method) => `HOST_IPC_FAILED: ${pluginName}.${method} 调用失败`, - hostUnavailable: (pluginName, method) => `HOST_UNAVAILABLE: ${pluginName}.${method} 宿主接口未就绪`, - callFailed: '调用失败', - movedToTrash: '已移入回收站', - deleteFailed: '删除失败', - revealedInFolder: '已定位文件', - revealFailed: '定位失败', - opened: '已打开', - openFailed: '打开失败', - pluginCallNotReady: '插件调用未就绪' - }, - 'en-US': { - ipcCallFailed: 'IPC call failed', - ipcInnerFailed: 'Internal IPC call failed', - scanIncomplete: 'Incomplete scan results', - dirReadFailed: (details, moreCount) => - `Directory read failed or incomplete: ${details}${moreCount > 0 ? `; and ${moreCount} more` : ''}`, - dirEntrySep: '; ', - dirErrorColon: ': ', - deepScanUnavailable: 'Deep scan unavailable; only top-level directory listed (incomplete)', - pathEmpty: 'Path cannot be empty', - invalidMethodEmpty: 'INVALID_METHOD: Method name cannot be empty', - invalidMethodFormat: 'INVALID_METHOD_FORMAT: Method name contains invalid characters or is too long', - invalidParamsObject: 'INVALID_PARAMS: Parameters must be a non-null object', - paramTooLong: (key) => `PARAM_TOO_LONG: Parameter "${key}" exceeds maximum length`, - paramOutOfRange: (key) => `PARAM_OUT_OF_RANGE: Numeric parameter "${key}" is out of range or non-finite`, - methodParamEmpty: 'Method parameter cannot be empty', - invalidMethodType: 'INVALID_METHOD: Method must be a non-empty string', - malformedDllResponse: 'MALFORMED_DLL_RESPONSE: Native component returned malformed JSON', - unknownDllError: 'Native component returned an unknown error', - hostIpcFailed: (pluginName, method) => `HOST_IPC_FAILED: ${pluginName}.${method} call failed`, - hostUnavailable: (pluginName, method) => `HOST_UNAVAILABLE: ${pluginName}.${method} host interface not ready`, - callFailed: 'Call failed', - movedToTrash: 'Moved to Trash', - deleteFailed: 'Delete failed', - revealedInFolder: 'Revealed in folder', - revealFailed: 'Failed to reveal item', - opened: 'Opened', - openFailed: 'Failed to open', - pluginCallNotReady: 'Plugin invocation not ready' - } -} - -function ipcStrings() { - const locale = getLocale() - return NATIVE_IPC_MESSAGES[locale] ?? NATIVE_IPC_MESSAGES['en-US'] -} -/** - * ZTools 真实宿主 IPC 与系统能力桥接层 (Real Host IPC Bridge) - * - * 严格遵循《ZTools Declarative UI 2.0 架构与 35 款原生插件全量升级规范》5.1 真实环境铁律: - * - 在真实 Electron 宿主环境中,100% 走通 Preload (__ztoolsElectron.transport.methods / window.ztools / __ztoolsLauncher) 真实调用链路 - * - 严禁在真实环境中因参数格式或嵌套响应结构差异而回退到假数据 - */ - -let ipcReqSeq = 1 -const realFileSizeCache = new Map() - -export function nextMessageId(prefix = 'ipc'): string { - ipcReqSeq = (ipcReqSeq + 1) % 1_000_000 - return `${prefix}_${Date.now()}_${ipcReqSeq}` -} - -/** - * 判断当前是否处于真实的 ZTools Electron 渲染进程宿主环境 - */ -export function isRealElectronHost(hostOverride?: unknown): boolean { - if (hostOverride) return false - if (typeof window === 'undefined') return false - const w = window as DynamicBridge - return Boolean( - w.__ztoolsElectron?.transport?.methods || - w.ztools?.transport?.call || - w.ztools?.transport?.methods - ) -} - -function normalizeMethodParams(method: string, params: Record): Record { - if (!params || typeof params !== 'object') return {} - const next = { ...params } - if (method === 'system_get_disk_usage') { - const rawDrive = String(next.drive || next.path || 'C:\\').trim() - if (rawDrive.startsWith('/')) { - next.drive = rawDrive - } else { - const match = rawDrive.match(/^([A-Za-z]):/) - next.drive = match ? `${match[1].toUpperCase()}:\\` : rawDrive.replace(/\//g, '\\') - } - delete next.path - } - return next -} - -function normalizeMethodResult(method: string, payload: DynamicBridge): DynamicBridge { - if (!payload || typeof payload !== 'object') return payload - - if (method === 'system_get_disk_usage') { - const avail = typeof payload.available === 'number' - ? payload.available - : typeof payload.free === 'number' - ? payload.free - : Math.max(0, Number(payload.total || 0) - Number(payload.used || 0)) - return { - ...payload, - available: avail, - free: avail - } - } - - if (method === 'system_get_hardware_summary') { - const cpuModel = - typeof payload.cpuModel === 'string' && payload.cpuModel.trim() - ? payload.cpuModel.trim() - : Array.isArray(payload.cpuModels) && payload.cpuModels.length > 0 - ? String(payload.cpuModels[0]).trim() - : 'x86_64 Processor' - return { - ...payload, - cpuModel - } - } - - if (method === 'system_get_battery_status') { - // 宿主约定 percent 超出 0-100(如 255)表示无电池或电量未知,不能改写成 100% - // 若宿主明确给出 hasBattery 布尔值,必须原样保留,仅在缺失时按合法电量推算 - const rawPct = payload.percent - const validPct = typeof rawPct === 'number' && Number.isFinite(rawPct) && rawPct >= 0 && rawPct <= 100 - const hasBattery = typeof payload.hasBattery === 'boolean' ? payload.hasBattery : validPct - return { - ...payload, - percent: validPct ? rawPct : null, - hasBattery - } - } - - if (method === 'screen_get_all_displays') { - const list = Array.isArray(payload) - ? payload - : Array.isArray(payload.displays) - ? payload.displays - : [] - return list.map((d: DynamicBridge) => ({ - ...d, - label: d?.label || d?.name || `Display #${d?.id ?? 1}` - })) - } - - return payload -} - -function extractIpcErrorMeta(errObj: DynamicBridge): { - errorCode?: string - errorDetails?: Record -} { - if (!errObj || typeof errObj !== 'object') return {} - const errorCode = - typeof errObj.errorCode === 'string' && errObj.errorCode.trim() - ? errObj.errorCode.trim() - : typeof errObj.code === 'string' && errObj.code.trim() - ? errObj.code.trim() - : undefined - const rawDetails = - errObj.errorDetails && typeof errObj.errorDetails === 'object' && !Array.isArray(errObj.errorDetails) - ? (errObj.errorDetails as Record) - : errObj.details && typeof errObj.details === 'object' && !Array.isArray(errObj.details) - ? (errObj.details as Record) - : undefined - return { - ...(errorCode ? { errorCode } : {}), - ...(rawDetails ? { errorDetails: rawDetails } : {}) - } -} - -function unwrapTransportResponse( - method: string, - raw: DynamicBridge -): { ok: boolean; data?: DynamicBridge; error?: string; errorCode?: string; errorDetails?: Record } { - if (raw === null || raw === undefined) { - return { ok: false, error: 'EMPTY_IPC_RESPONSE', errorCode: 'EMPTY_IPC_RESPONSE' } - } - if (typeof raw !== 'object') { - return { ok: true, data: raw } - } - if (raw.success === false) { - const errObj = raw.error - const errMsg = - typeof errObj === 'object' && errObj !== null - ? String(errObj.message || errObj.code || JSON.stringify(errObj)) - : String(errObj || ipcStrings().ipcCallFailed) - return { ok: false, error: errMsg, ...extractIpcErrorMeta(raw), ...extractIpcErrorMeta(errObj) } - } - - const firstLayer = 'data' in raw && raw.data !== undefined ? raw.data : raw - if (firstLayer && typeof firstLayer === 'object' && !Array.isArray(firstLayer)) { - if (firstLayer.success === false) { - const errObj = firstLayer.error - const errMsg = - typeof errObj === 'object' && errObj !== null - ? String(errObj.message || errObj.code || JSON.stringify(errObj)) - : String(errObj || ipcStrings().ipcInnerFailed) - return { ok: false, error: errMsg, ...extractIpcErrorMeta(firstLayer), ...extractIpcErrorMeta(errObj) } - } - if ('data' in firstLayer && firstLayer.data !== undefined) { - return { ok: true, data: normalizeMethodResult(method, firstLayer.data) } - } - } - - return { ok: true, data: normalizeMethodResult(method, firstLayer) } -} - -/** - * 调用 Electron Preload Transport 方法(自动封装合法的 alphanumeric messageId 与双层解包) - */ -export async function callHostTransport( - method: string, - params: Record = {}, - hostOverride?: DynamicBridge -): Promise<{ ok: boolean; data?: T; error?: string; errorCode?: string; errorDetails?: Record }> { - const normalizedParams = normalizeMethodParams(method, params) - - // 1. 测试注入的 hostOverride 优先 - if (hostOverride) { - if (typeof hostOverride[method] === 'function') { - try { - const res = await hostOverride[method](normalizedParams) - const unwrapped = unwrapTransportResponse(method, res) - return unwrapped as { ok: boolean; data?: T; error?: string; errorCode?: string; errorDetails?: Record } - } catch (err: DynamicBridge) { - return { ok: false, error: err instanceof Error ? err.message : String(err), ...extractIpcErrorMeta(err) } - } - } - if (typeof hostOverride?.transport?.call === 'function') { - try { - const res = await hostOverride.transport.call(method, normalizedParams) - const unwrapped = unwrapTransportResponse(method, res) - return unwrapped as { ok: boolean; data?: T; error?: string; errorCode?: string; errorDetails?: Record } - } catch (err: DynamicBridge) { - return { ok: false, error: err instanceof Error ? err.message : String(err), ...extractIpcErrorMeta(err) } - } - } - } - - if (typeof window === 'undefined') { - return { ok: false, error: 'NO_WINDOW_ENV', errorCode: 'NO_WINDOW_ENV' } - } - - const w = window as DynamicBridge - const methods = w.__ztoolsElectron?.transport?.methods || w.ztools?.transport?.methods - const fn = methods?.[method] - - if (typeof fn === 'function') { - try { - const messageId = nextMessageId(method.replace(/[^A-Za-z0-9_]/g, '_').slice(0, 24)) - const raw = await fn({ messageId, params: normalizedParams }) - return unwrapTransportResponse(method, raw) as { ok: boolean; data?: T; error?: string; errorCode?: string; errorDetails?: Record } - } catch (err: DynamicBridge) { - return { ok: false, error: err instanceof Error ? err.message : String(err), ...extractIpcErrorMeta(err) } - } - } - - if (typeof w.ztools?.transport?.call === 'function') { - try { - const raw = await w.ztools.transport.call(method, normalizedParams) - return unwrapTransportResponse(method, raw) as { ok: boolean; data?: T; error?: string; errorCode?: string; errorDetails?: Record } - } catch (err: DynamicBridge) { - return { ok: false, error: err instanceof Error ? err.message : String(err), ...extractIpcErrorMeta(err) } - } - } - - return { ok: false, error: `METHOD_NOT_AVAILABLE: ${method}`, errorCode: 'METHOD_NOT_AVAILABLE' } -} - -export interface RealDiskDriveInfo { - drive: string - totalBytes: number - usedBytes: number - availableBytes: number - usagePercent: number -} - -/** - * 探测本机全部真实挂载磁盘分区 (C:\ ~ Z:\ 或 macOS/POSIX 挂载点 '/') - */ -export async function probeRealDiskDrives( - candidateLetters: string[] = ['C', 'D', 'E', 'F', 'G'], - hostOverride?: DynamicBridge -): Promise { - const drives: RealDiskDriveInfo[] = [] - const results = await Promise.all( - candidateLetters.map(async (letter) => { - const raw = String(letter || '').trim() - const isPosix = raw.startsWith('/') - const drivePath = isPosix ? raw : `${raw.replace(/:\\?$/, '').toUpperCase()}:\\` - const res = await callHostTransport<{ - total: number - used: number - available: number - free?: number - percent: number - }>('system_get_disk_usage', { drive: drivePath }, hostOverride) - if (res.ok && res.data && typeof res.data.total === 'number' && res.data.total > 0) { - const availableBytes = - typeof res.data.available === 'number' - ? res.data.available - : typeof res.data.free === 'number' - ? res.data.free - : Math.max(0, res.data.total - res.data.used) - return { - drive: isPosix ? raw : `${raw.replace(/:\\?$/, '').toUpperCase()}:`, - totalBytes: res.data.total, - usedBytes: res.data.used, - availableBytes, - usagePercent: res.data.percent - } - } - return null - }) - ) - - for (const item of results) { - if (item) drives.push(item) - } - - if (drives.length === 0 && !candidateLetters.includes('/')) { - const posixRes = await callHostTransport<{ - total: number - used: number - available: number - free?: number - percent: number - }>('system_get_disk_usage', { drive: '/' }, hostOverride) - if (posixRes.ok && posixRes.data && typeof posixRes.data.total === 'number' && posixRes.data.total > 0) { - const availableBytes = - typeof posixRes.data.available === 'number' - ? posixRes.data.available - : typeof posixRes.data.free === 'number' - ? posixRes.data.free - : Math.max(0, posixRes.data.total - posixRes.data.used) - drives.push({ - drive: '/', - totalBytes: posixRes.data.total, - usedBytes: posixRes.data.used, - availableBytes, - usagePercent: posixRes.data.percent - }) - } - } - - return drives -} - -/** - * 获取本机真实系统特殊路径(支持 home 派生标准子目录兜底,自动兼容 Windows 与 macOS/POSIX) - */ -export async function getRealSystemPath( - name: 'home' | 'appData' | 'userData' | 'desktop' | 'documents' | 'downloads' | 'music' | 'pictures' | 'videos' | 'temp' | 'cache', - hostOverride?: DynamicBridge -): Promise { - const res = await callHostTransport('system_get_path', { name }, hostOverride) - if (res.ok && res.data) { - if (typeof res.data === 'string' && res.data.trim().length > 0) { - return res.data.trim() - } - if (typeof res.data.path === 'string' && res.data.path.trim().length > 0) { - return res.data.path.trim() - } - } - - if (name !== 'home') { - const home = await getRealSystemPath('home', hostOverride) - if (home) { - const isPosix = home.startsWith('/') - const subMap: Record = isPosix - ? { - desktop: `${home}/Desktop`, - documents: `${home}/Documents`, - downloads: `${home}/Downloads`, - music: `${home}/Music`, - pictures: `${home}/Pictures`, - videos: `${home}/Videos`, - appData: `${home}/Library/Application Support`, - userData: `${home}/Library/Application Support/ZTools`, - temp: '/tmp', - cache: `${home}/Library/Caches` - } - : { - desktop: `${home}\\Desktop`, - documents: `${home}\\Documents`, - downloads: `${home}\\Downloads`, - music: `${home}\\Music`, - pictures: `${home}\\Pictures`, - videos: `${home}\\Videos`, - appData: `${home}\\AppData\\Roaming`, - userData: `${home}\\AppData\\Roaming\\ZTools`, - temp: `${home}\\AppData\\Local\\Temp`, - cache: `${home}\\AppData\\Local` - } - if (subMap[name]) return subMap[name] - } - } - - return '' -} - -export type RealDriveUsageInfo = RealDiskDriveInfo - -export interface RealIndexedFileEntry { - name: string - path: string - ext: string - isDir: boolean - isDirectory: boolean - size: number - sizeBytes: number - mtime: number - mtimeMs: number - lastModifiedMs: number -} - -export interface RealDirectorySubdirSummary { - name: string - path: string - fileCount: number - totalBytes: number - mtime: number - /** 体积不是完整统计(宿主扫描截断且独立统计超时 / 无权限),totalBytes 只是下限 */ - approximate?: boolean -} - -export interface RealDirectoryScanResult extends Iterable { - files: RealIndexedFileEntry[] - totalFiles: number - fileCount: number - totalBytes: number - subdirs: RealDirectorySubdirSummary[] - /** 宿主扫描达到条目上限后停止:files / totalFiles 只是已遍历部分的抽样 */ - truncated?: boolean - /** totalBytes 为近似值(下限) */ - approximate?: boolean - /** 宿主实际遍历的条目数 */ - visitedEntries?: number - /** 目录本身不存在(ENOENT) */ - missing?: boolean - /** 读取失败的真实原因;已有文件仍可使用,但不能当作完整结果。 */ - error?: string -} - -interface ScanResultMeta { - truncated?: boolean - approximate?: boolean - visitedEntries?: number - missing?: boolean -} - -export interface ScanDirectoryTreeOptions { - maxDepth?: number - maxFiles?: number - collectTopN?: number - filterExt?: RegExp - /** 为 true 时,目录本身不存在(ENOENT)按空目录处理,不返回 error(权限拒绝/读取失败仍照常报错) */ - ignoreMissing?: boolean - /** Top-N 保留与排序方式:默认按体积降序,下载/录屏等时效场景可传 mtime-desc */ - sortBy?: 'size-desc' | 'mtime-desc' - hostOverride?: DynamicBridge -} - -function extractFileExt(fileNameOrPath: string): string { - const base = String(fileNameOrPath || '').split(/[\\/]/).pop() || '' - const dotIdx = base.lastIndexOf('.') - return dotIdx > 0 ? base.slice(dotIdx).toLowerCase() : '' -} - -function normalizeIndexedFileEntry(f: DynamicBridge): RealIndexedFileEntry { - const p = String(f?.path || '') - const name = String(f?.name || p.split(/[\\/]/).pop() || '') - const sz = Number(f?.size ?? f?.sizeBytes ?? 0) - const isDir = Boolean(f?.is_dir || f?.isDir || f?.isDirectory) - const rawMtime = Number(f?.mtime ?? f?.mtimeMs ?? 0) - const validMtime = Number.isFinite(rawMtime) && rawMtime > 0 - const mtimeMs = validMtime ? (rawMtime > 1e11 ? rawMtime : rawMtime * 1000) : 0 - const mtimeSec = validMtime ? (rawMtime > 1e11 ? Math.floor(rawMtime / 1000) : rawMtime) : 0 - if (p && sz >= 0) realFileSizeCache.set(p, sz) - return { - name, - path: p, - ext: extractFileExt(name || p), - isDir, - isDirectory: isDir, - size: sz, - sizeBytes: sz, - mtime: mtimeSec, - mtimeMs, - lastModifiedMs: mtimeMs - } -} - -function makeScanResult( - files: RealIndexedFileEntry[], - totalFiles: number, - totalBytes: number, - subdirs: RealDirectorySubdirSummary[], - meta: ScanResultMeta = {} -): RealDirectoryScanResult { - return { - files, - totalFiles, - fileCount: totalFiles, - totalBytes, - subdirs, - ...(meta.truncated ? { truncated: true } : {}), - ...(meta.approximate ? { approximate: true } : {}), - ...(meta.missing ? { missing: true } : {}), - ...(typeof meta.visitedEntries === 'number' ? { visitedEntries: meta.visitedEntries } : {}), - [Symbol.iterator]() { - return files[Symbol.iterator]() - } - } -} - -/** - * 调用客户端的原生文件索引组件 (ztools-indexer) 检索文件 - */ -export async function searchRealIndexedFiles( - query: string, - limit = 40, - hostOverride?: DynamicBridge -): Promise { - if (!query || !query.trim()) return [] - const q = query.trim() - const safeLimit = Math.min(200, Math.max(1, Math.floor(limit || 40))) - - try { - const res = await callHostTransport<{ files?: DynamicBridge[] }>( - 'system_search_files', - { query: q, limit: safeLimit }, - hostOverride - ) - if (res.ok && res.data && Array.isArray(res.data.files)) { - return res.data.files.map(normalizeIndexedFileEntry) - } - - if (!hostOverride && typeof window !== 'undefined') { - const w = window as DynamicBridge - if (typeof w.__ztoolsLauncher?.searchFiles === 'function') { - const rawOuter = await w.__ztoolsLauncher.searchFiles(q, safeLimit) - const raw = rawOuter && typeof rawOuter === 'object' && 'data' in rawOuter && rawOuter.data ? rawOuter.data : rawOuter - if (raw && Array.isArray(raw.files)) { - return raw.files.map(normalizeIndexedFileEntry) - } - } - } - } catch { - // ignore - } - return [] -} - -/** - * 深度扫描指定真实物理目录树(支持符号链接穿透,如 AppData\Roaming\Tencent -> D:\Local\Roaming\Tencent) - * 返回该目录下 Top 文件列表、全树真实文件总数、全树真实总字节数与一级子目录汇总 - */ -export async function scanRealDirectoryTree( - dirPath: string, - limitOrOptions: number | ScanDirectoryTreeOptions = 160, - hostOverrideArg?: DynamicBridge -): Promise { - const result = await scanDirectoryTreeWithError(dirPath, limitOrOptions, hostOverrideArg) - return result.error ? { ...result.scan, error: result.error } : result.scan -} - -/** 仅当正则明确声明了扩展名(含 `\.`)时提取后缀列表,避免把 `thumbcache|iconcache` 等文件名关键词误拆成假扩展名 */ -function extractExtensionTokensFromFilter(filterExt: RegExp): string[] { - const src = filterExt.source - if (!src.includes('\\.')) return [] - const afterDot = src.slice(src.indexOf('\\.') + 2) - const rawTokens = afterDot.match(/[a-z0-9]{1,8}/gi) || [] - const seen = new Set() - const out: string[] = [] - for (const token of rawTokens) { - const lower = token.toLowerCase() - if (!lower || seen.has(lower)) continue - seen.add(lower) - out.push(lower) - } - return out -} - -function isMissingDirectoryError(res: { error?: string; errorCode?: string; errorDetails?: Record }): boolean { - if (res.errorDetails?.reason === 'ENOENT' || res.errorCode === 'ENOENT') return true - const msg = String(res.error || '') - return /Directory does not exist|ENOENT/i.test(msg) -} - -/** 一次界面扫描的错误汇总;多个目录并行扫描时保留可读目录的结果。 */ -export function createDirectoryScanner(hostOverride?: DynamicBridge) { - const failures = new Map() - return { - async scan(dir: string, options: number | ScanDirectoryTreeOptions = 160) { - const result = await scanRealDirectoryTree(dir, options, hostOverride) - const ignoreMissing = typeof options === 'object' && options !== null && options.ignoreMissing === true - const error = - result.missing && ignoreMissing - ? '' - : result.error || (result.truncated || result.approximate ? ipcStrings().scanIncomplete : '') - if (error) failures.set(dir, error) - else failures.delete(dir) - return result - }, - get error(): string | undefined { - if (!failures.size) return undefined - const s = ipcStrings() - const details = [...failures].slice(0, 3).map(([dir, error]) => `${dir}${s.dirErrorColon}${error}`).join(s.dirEntrySep) - return s.dirReadFailed(details, Math.max(0, failures.size - 3)) - } - } -} - -/** scanRealDirectoryTree 的实现:额外带回读取失败原因(目录不存在 / 为空 / 无权限 / 载荷异常) */ -async function scanDirectoryTreeWithError( - dirPath: string, - limitOrOptions: number | ScanDirectoryTreeOptions, - hostOverrideArg?: DynamicBridge -): Promise<{ scan: RealDirectoryScanResult; error?: string }> { - const empty = makeScanResult([], 0, 0, []) - if (!dirPath || !dirPath.trim()) return { scan: empty, error: 'EMPTY_DIRECTORY_PATH' } - const targetDir = dirPath.trim() - - const opts: ScanDirectoryTreeOptions = - typeof limitOrOptions === 'number' - ? { maxFiles: limitOrOptions, hostOverride: hostOverrideArg } - : { ...limitOrOptions, hostOverride: limitOrOptions?.hostOverride ?? hostOverrideArg } - - const rawLimit = opts.maxFiles ?? opts.collectTopN ?? 160 - const safeLimit = Math.min(200, Math.max(1, Math.floor(rawLimit || 160))) - const hostOverride = opts.hostOverride - const filterExt = opts.filterExt - const ignoreMissing = opts.ignoreMissing === true - const dirQuery = `dir:${targetDir}` - - try { - let rawPayload: DynamicBridge = null - const searchParams: Record = { - query: dirQuery, - limit: safeLimit, - ...(opts.sortBy ? { sortBy: opts.sortBy } : {}) - } - const res = await callHostTransport( - 'system_search_files', - searchParams, - hostOverride - ) - if (res.ok && res.data && res.data.degraded !== true) { - rawPayload = res.data - } else if (!res.ok && ignoreMissing && isMissingDirectoryError(res)) { - const missingScan = makeScanResult([], 0, 0, [], { missing: true }) - return { scan: missingScan } - } - if (!rawPayload && !hostOverride && res.errorCode === 'METHOD_NOT_AVAILABLE' && typeof window !== 'undefined') { - const w = window as DynamicBridge - if (typeof w.__ztoolsLauncher?.searchFiles === 'function') { - const rawOuter = await w.__ztoolsLauncher.searchFiles(dirQuery, safeLimit) - const candidate = - rawOuter && typeof rawOuter === 'object' && 'data' in rawOuter && rawOuter.data - ? rawOuter.data - : rawOuter - if (candidate && candidate.degraded !== true && candidate.success !== false) { - rawPayload = candidate - } - } - } - - if ( - rawPayload && - Array.isArray(rawPayload.files) - ) { - let files: RealIndexedFileEntry[] = rawPayload.files.map(normalizeIndexedFileEntry) - if (filterExt instanceof RegExp) { - files = files.filter(f => !f.isDir && (filterExt.test(f.name) || filterExt.test(f.ext))) - // 若目录 Top-N 大文件均为其他后缀,使用 MFT 索引直接检索明确声明的目标扩展名 - if (files.length === 0 && !hostOverride) { - const extTokens = extractExtensionTokensFromFilter(filterExt) - if (extTokens.length > 0) { - // 只接受确实位于目标目录下的检索结果,不能用别处同后缀文件冒充目录内容 - const prefixLower = `${targetDir.replace(/[\\/]+$/, '')}${isWindowsStylePath(targetDir) ? '\\' : '/'}`.toLowerCase() - const extraLists = await Promise.all( - extTokens.map(ext => searchRealIndexedFiles(`.${ext}`, 30, hostOverride)) - ) - const seen = new Set() - for (const list of extraLists) { - for (const item of list) { - if (!item.isDir && item.size > 0 && !seen.has(item.path)) { - if (item.path.replace(/\//g, isWindowsStylePath(targetDir) ? '\\' : '/').toLowerCase().startsWith(prefixLower)) { - seen.add(item.path) - files.push(item) - } - } - } - } - } - } - } - // 先基于过滤后的完整命中集合计算总文件数与总字节数,再按 collectTopN 裁剪样本列表 - const matchedCount = files.length - const matchedBytes = files.reduce((acc, f) => acc + (f.isDir ? 0 : f.size), 0) - if (typeof opts.collectTopN === 'number' && opts.collectTopN > 0 && files.length > opts.collectTopN) { - files = files.slice(0, opts.collectTopN) - } - const subdirs: RealDirectorySubdirSummary[] = Array.isArray(rawPayload.subdirs) - ? rawPayload.subdirs.map((s: DynamicBridge) => ({ - name: String(s.name || ''), - path: String(s.path || ''), - fileCount: Number(s.file_count ?? s.fileCount ?? 0), - totalBytes: Number(s.total_bytes ?? s.totalBytes ?? 0), - mtime: Number(s.mtime || 0), - ...(s.approximate === true ? { approximate: true } : {}) - })) - : [] - const totalFilesCount = - filterExt instanceof RegExp ? matchedCount : Number(rawPayload.total_matches ?? matchedCount) - const totalBytesCount = - filterExt instanceof RegExp ? matchedBytes : Number(rawPayload.total_bytes ?? matchedBytes) - const visited = Number(rawPayload.visited_entries) - return { - scan: makeScanResult(files, totalFilesCount, totalBytesCount, subdirs, { - truncated: rawPayload.truncated === true, - approximate: rawPayload.approximate === true, - ...(Number.isFinite(visited) && visited >= 0 ? { visitedEntries: visited } : {}) - }), - ...(typeof rawPayload.scan_error === 'string' && rawPayload.scan_error ? { error: rawPayload.scan_error } : {}) - } - } - - // 深度扫描失败或回执无效时,仅以一级目录读取补回可见结果;不冒充完整目录树。 - const listing = await listDirectoryViaFilesystem(targetDir, hostOverride, { withSizes: true, limit: safeLimit }) - if (listing.ok && listing.entries.length > 0) { - const files: RealIndexedFileEntry[] = [] - let totalBytes = 0 - for (const entry of listing.entries) { - if (filterExt instanceof RegExp && !filterExt.test(entry.name) && !filterExt.test(entry.ext)) { - continue - } - files.push(entry) - totalBytes += entry.isDir ? 0 : entry.size - } - const incomplete = listing.entries.some(entry => entry.isDir) || listing.entries.length >= safeLimit - return { - scan: makeScanResult(files, files.filter(file => !file.isDir).length, totalBytes, [], { approximate: incomplete }), - ...(incomplete ? { error: res.error || ipcStrings().deepScanUnavailable } : {}) - } - } - return listing.ok ? { scan: empty } : { scan: empty, error: listing.error || 'DIRECTORY_READ_FAILED' } - } catch (error) { - return { scan: empty, error: error instanceof Error ? error.message : String(error) } - } -} - - -/** 目录读取不到任何条目(不存在 / 为空 / 无权限)时的错误码 */ -export const DIRECTORY_EMPTY_OR_UNREADABLE = 'DIRECTORY_EMPTY_OR_UNREADABLE' - -export interface RealDirectoryListingResult { - /** 目录内条目的完整路径;读取失败时为空数组 */ - entries: string[] - /** 读取失败或目录为空时的错误码 / 宿主错误信息 */ - error?: string -} - -export interface RealDirectChildrenResult { - /** 目录的直接子项(子目录在前),按路径去重 */ - entries: RealIndexedFileEntry[] - /** 宿主扫描达到条目上限,可能只返回了部分直接子项 */ - partial: boolean - error?: string -} - -function stripTrailingSeparators(p: string): string { - const trimmed = p.replace(/[\\/]+$/, '') - return trimmed || p.slice(0, 1) -} - -function isWindowsStylePath(p: string): boolean { - return /^[A-Za-z]:/.test(p) || p.startsWith('\\\\') || (p.includes('\\') && !p.includes('/')) -} - -function comparablePath(p: string): string { - const stripped = stripTrailingSeparators(String(p || '').trim()) - return isWindowsStylePath(stripped) ? stripped.replace(/\//g, '\\').toLowerCase() : stripped -} - -function parentDirOf(p: string): string { - const stripped = stripTrailingSeparators(String(p || '')) - const idx = Math.max(stripped.lastIndexOf('/'), stripped.lastIndexOf('\\')) - if (idx < 0) return '' - if (idx === 0) return stripped.slice(0, 1) - const parent = stripped.slice(0, idx) - return /^[A-Za-z]:$/.test(parent) ? `${parent}\\` : parent -} - -function isDirectChildPath(dirPath: string, candidate: string): boolean { - if (!candidate) return false - return comparablePath(parentDirOf(candidate)) === comparablePath(dirPath) -} - -function joinChildPath(dirPath: string, name: string): string { - const sep = isWindowsStylePath(dirPath) ? '\\' : '/' - const base = dirPath.replace(/[\\/]+$/, '') - return `${base}${sep}${name}` -} - -/** - * 通过 filesystem_get_directory_contents 读取一级目录(需宿主授权)。 - * 宿主真实返回 { success, files: [{ name, size, isDirectory, lastModified }] }(name 为文件名); - * 兼容旧测试替身返回的完整路径字符串数组。 - */ -async function listDirectoryViaFilesystem( - dirPath: string, - hostOverride: DynamicBridge, - options: { withSizes?: boolean; limit?: number } = {} -): Promise<{ ok: boolean; entries: RealIndexedFileEntry[]; error?: string }> { - const res = await callHostTransport('filesystem_get_directory_contents', { path: dirPath }, hostOverride) - if (!res.ok) return { ok: false, entries: [], error: res.error || 'DIRECTORY_READ_FAILED' } - const data = res.data - const rawList: unknown[] | null = Array.isArray(data) ? data : Array.isArray(data?.files) ? data.files : null - if (!rawList) return { ok: false, entries: [], error: 'INVALID_DIRECTORY_PAYLOAD' } - - const limit = Math.max(1, Math.floor(options.limit ?? 1000)) - const nowSec = Math.floor(Date.now() / 1000) - const entries: RealIndexedFileEntry[] = [] - const seen = new Set() - for (const item of rawList) { - if (entries.length >= limit) break - let entry: RealIndexedFileEntry | null = null - if (typeof item === 'string') { - const itemPath = item.trim() - if (!itemPath) continue - const name = itemPath.split(/[\\/]/).pop() || itemPath - const sz = options.withSizes ? await getRealFileSize(itemPath, hostOverride) : 0 - entry = normalizeIndexedFileEntry({ - name, - path: itemPath, - isDir: sz === 0 && !name.includes('.'), - size: sz, - mtime: nowSec - }) - } else if (item && typeof item === 'object' && typeof (item as DynamicBridge).name === 'string') { - const raw = item as DynamicBridge - const rawName = raw.name.trim() - if (!rawName || rawName === '.' || rawName === '..') continue - // 只接受文件名,或确实位于该目录下的完整路径,拒绝越界路径 - const fullPath = /[\\/]/.test(rawName) ? rawName : joinChildPath(dirPath, rawName) - if (!isDirectChildPath(dirPath, fullPath)) continue - const isDir = Boolean(raw.isDirectory ?? raw.isDir ?? raw.is_dir) - const parsedMtime = Date.parse(String(raw.lastModified || '')) - entry = normalizeIndexedFileEntry({ - name: fullPath.split(/[\\/]/).pop() || rawName, - path: fullPath, - isDir, - size: isDir ? 0 : Math.max(0, Number(raw.size) || 0), - mtime: Number.isFinite(parsedMtime) ? parsedMtime : nowSec - }) - } - if (!entry || seen.has(entry.path)) continue - seen.add(entry.path) - entries.push(entry) - } - return { ok: true, entries } -} - -/** - * 读取真实目录下的条目路径(真实宿主中优先走 dir: 扫描:一级子目录 + 全树 Top-N 大文件),并返回失败原因。 - * 目录不存在、为空或无权限时返回空列表与错误码,绝不用全盘关键词搜索结果冒充目录内容。 - */ -export async function listRealDirectoryContentsResult( - dirPath: string, - hostOverride?: DynamicBridge -): Promise { - if (!dirPath || !dirPath.trim()) return { entries: [], error: 'EMPTY_DIRECTORY_PATH' } - const targetDir = dirPath.trim() - - if (!hostOverride && isRealElectronHost()) { - const tree = await scanRealDirectoryTree(targetDir, 60) - const paths: string[] = [] - for (const s of tree.subdirs) { - if (s.path) paths.push(s.path) - } - for (const f of tree.files) { - if (f.path) paths.push(f.path) - } - if (paths.length > 0) return { entries: Array.from(new Set(paths)) } - } - - const listing = await listDirectoryViaFilesystem(targetDir, hostOverride) - if (!listing.ok) return { entries: [], error: listing.error } - if (listing.entries.length === 0) return { entries: [], error: DIRECTORY_EMPTY_OR_UNREADABLE } - return { entries: listing.entries.map(e => e.path) } -} - -/** - * 读取真实目录下的条目路径(保持旧签名:失败时返回空数组,需要失败原因请用 listRealDirectoryContentsResult) - */ -export async function listRealDirectoryContents( - dirPath: string, - hostOverride?: DynamicBridge -): Promise { - return (await listRealDirectoryContentsResult(dirPath, hostOverride)).entries -} - -/** - * 只列出目录的直接子项(子目录 + 直接位于该目录下的文件),用于文件夹预览、按目录改名等场景。 - * dir: 扫描结果中只保留 subdirs 与父目录等于 dirPath 的文件;扫描达到上限时 partial=true,由插件如实提示「仅显示部分」。 - */ -export async function listDirectChildren( - dirPath: string, - hostOverride?: DynamicBridge -): Promise { - if (!dirPath || !dirPath.trim()) return { entries: [], partial: false, error: 'EMPTY_DIRECTORY_PATH' } - const targetDir = dirPath.trim() - const scanLimit = 200 - const entries: RealIndexedFileEntry[] = [] - const seen = new Set() - const push = (entry: RealIndexedFileEntry) => { - const key = comparablePath(entry.path) - if (!entry.path || seen.has(key)) return - seen.add(key) - entries.push(entry) - } - - const { scan: tree, error } = await scanDirectoryTreeWithError(targetDir, { maxFiles: scanLimit, hostOverride }) - for (const s of tree.subdirs) { - if (!s.path || !isDirectChildPath(targetDir, s.path)) continue - push( - normalizeIndexedFileEntry({ - name: s.name || s.path.split(/[\\/]/).pop(), - path: s.path, - isDir: true, - size: s.totalBytes, - mtime: s.mtime - }) - ) - } - let directFileCount = 0 - for (const f of tree.files) { - if (!isDirectChildPath(targetDir, f.path)) continue - directFileCount++ - push(f) - } - // 宿主 total_matches 是全树文件数、subdirs[].file_count 是各子目录全树文件数,差值即直接子文件数; - // 拿到的直接子文件少于它就说明被 Top-N 截断了。计数不可用时按是否达到扫描上限判断 - const expectedDirectFiles = tree.totalFiles - tree.subdirs.reduce((sum, d) => sum + (Number(d.fileCount) || 0), 0) - const partial = - Number.isFinite(expectedDirectFiles) && expectedDirectFiles >= 0 - ? directFileCount < expectedDirectFiles - : tree.files.length >= scanLimit - if (entries.length > 0) { - return { entries, partial } - } - - if (tree.files.length > 0) { - // dir: 扫描只返回了深层文件(直接子文件被 Top-N 截掉),如实标注部分结果 - return { entries: [], partial: true, error: DIRECTORY_EMPTY_OR_UNREADABLE } - } - return { entries: [], partial: false, error: error || DIRECTORY_EMPTY_OR_UNREADABLE } -} - -/** - * 获取真实文件字节大小(优先用扫描结果里的大小,再走 filesystem_get_file_size);读不到时返回 0 - */ -export async function getRealFileSize( - filePath: string, - hostOverride?: DynamicBridge -): Promise { - if (!filePath) return 0 - if (!hostOverride && realFileSizeCache.has(filePath)) { - const cached = realFileSizeCache.get(filePath)! - if (cached > 0) return cached - } - const res = await callHostTransport('filesystem_get_file_size', { path: filePath }, hostOverride) - // 客户端返回 { success, size }(目录时 size 为 -1),旧的测试替身直接返回数字 - const size = typeof res.data === 'number' ? res.data : res.data?.size - if (res.ok && typeof size === 'number' && Number.isFinite(size) && size >= 0) { - realFileSizeCache.set(filePath, size) - return size - } - return 0 -} - -/** - * 在访达 / 资源管理器中定位并高亮文件或目录。 - * 定位失败直接返回 false,不能改用“打开”:对可执行文件那等于运行它。 - */ -export async function showRealItemInFolder( - fullPath: string, - hostOverride?: DynamicBridge -): Promise { - if (!fullPath) return false - const res = await callHostTransport('shell_show_item_in_folder', { fullPath }, hostOverride) - return res.ok -} - -/** - * 使用系统默认程序打开文件或目录 - */ -export async function openRealPath( - fullPath: string, - hostOverride?: DynamicBridge -): Promise { - if (!fullPath) return false - const res = await callHostTransport('shell_open_path', { fullPath }, hostOverride) - return res.ok -} - -/** - * 将真实文件或目录移入系统回收站(安全可恢复删除) - */ -export async function trashRealItem( - fullPath: string, - hostOverride?: DynamicBridge -): Promise<{ ok: boolean; error?: string; errorCode?: string; errorDetails?: Record }> { - if (!fullPath) return { ok: false, error: ipcStrings().pathEmpty } - const res = await callHostTransport('shell_trash_item', { fullPath }, hostOverride) - return { - ok: res.ok, - error: res.error, - ...(!res.ok && res.errorCode ? { errorCode: res.errorCode } : {}), - ...(!res.ok && res.errorDetails ? { errorDetails: res.errorDetails } : {}) - } -} - -export interface NativeInvocationResult { - ok: boolean - code: number - message: string - data?: T - error?: string - errorCode?: string - errorDetails?: Record -} - -export interface DllCapabilityResponse { - ok: boolean - code: number - data: T | null - message?: string - error?: string - errorCode?: string - errorDetails?: Record - pluginName: string - method: string - fromFallback?: boolean -} - -/** 声明式能力菜单项及其调用回执,供相同宿主协议的插件共用。 */ -export interface CapabilityActionItem { - id: string - title: string - subtitle: string - tag: string - method: string - params: Record -} - -export type PluginInvocationResult = Pick< - DllCapabilityResponse, 'ok' | 'pluginName' | 'method' | 'error' | 'errorCode' | 'errorDetails' | 'fromFallback' -> & { data?: unknown } - -/** 多个原生能力插件共用的参数边界校验;保护目标由各插件按自身业务提供。 */ -export function validateNativeCapabilityPayload( - method: string, - params: unknown, - forbiddenPattern: RegExp, - forbiddenReason: string -): { valid: boolean; error?: string } { - const s = ipcStrings() - if (typeof method !== 'string' || method.trim().length === 0) { - return { valid: false, error: s.invalidMethodEmpty } - } - if (method.length > 128 || !/^[A-Za-z0-9_]+$/.test(method.trim())) { - return { valid: false, error: s.invalidMethodFormat } - } - if (params === null || params === undefined || typeof params !== 'object' || Array.isArray(params)) { - return { valid: false, error: s.invalidParamsObject } - } - - const record = params as Record - for (const [key, val] of Object.entries(record)) { - if (typeof val === 'string') { - if (val.length > 4096) { - return { valid: false, error: s.paramTooLong(key) } - } - if (forbiddenPattern.test(val)) { - return { valid: false, error: `SECURITY_INTERCEPTED: ${forbiddenReason}` } - } - } else if (typeof val === 'number') { - if (!Number.isFinite(val) || val < -1000 || val > 100_000_000) { - return { valid: false, error: s.paramOutOfRange(key) } - } - } - } - - return { valid: true } -} - -export async function invokeDllPluginCapability( - pluginName: string, - method: string, - params: Record = {}, - hostBridge?: DynamicBridge, - offlineFallback?: () => T | Promise -): Promise> { - const s = ipcStrings() - if (!method || typeof method !== 'string' || method.trim().length === 0) { - return { - ok: false, - code: -1, - data: null, - message: s.methodParamEmpty, - error: s.invalidMethodType, - pluginName, - method: String(method || '') - } - } - - const trimmedMethod = method.trim() - - const unwrapDllRawPayload = (raw: unknown, unwrapDataProperty: boolean): DllCapabilityResponse => { - let parsed: DynamicBridge = raw - if (typeof raw === 'string') { - try { - parsed = JSON.parse(raw) - } catch { - throw new Error(s.malformedDllResponse) - } - } - if (parsed && typeof parsed === 'object') { - if ('error' in parsed && parsed.error !== undefined && parsed.error !== null && parsed.error !== '') { - const errMsg = `DLL_ERROR: ${String(parsed.error)}` - return { - ok: false, - code: typeof parsed.code === 'number' ? parsed.code : -1, - data: null, - message: errMsg, - error: errMsg, - ...extractIpcErrorMeta(parsed), - ...extractIpcErrorMeta(parsed.error), - pluginName, - method: trimmedMethod, - fromFallback: false - } - } - if ('ok' in parsed && parsed.ok === false) { - const errMsg = `DLL_ERROR: ${String(parsed.error || parsed.message || s.unknownDllError)}` - return { - ok: false, - code: typeof parsed.code === 'number' ? parsed.code : -1, - data: null, - message: errMsg, - error: errMsg, - ...extractIpcErrorMeta(parsed), - ...extractIpcErrorMeta(parsed.error), - pluginName, - method: trimmedMethod, - fromFallback: false - } - } - const dataPayload = unwrapDataProperty && 'data' in parsed && parsed.data !== undefined ? parsed.data : parsed - return { - ok: true, - code: typeof parsed.code === 'number' ? parsed.code : 0, - data: dataPayload as T, - message: typeof parsed.message === 'string' ? parsed.message : undefined, - pluginName, - method: trimmedMethod, - fromFallback: false - } - } - return { - ok: true, - code: 0, - data: (parsed ?? null) as T, - pluginName, - method: trimmedMethod, - fromFallback: false - } - } - - const wrapCaughtDllError = (err: unknown): DllCapabilityResponse => { - const message = err instanceof Error ? err.message : String(err) - if (message.startsWith('MALFORMED_DLL_RESPONSE:')) { - throw err - } - const errMsg = `NATIVE_CALL_FAILED: ${message}` - return { - ok: false, - code: -1, - data: null, - message: errMsg, - error: errMsg, - ...extractIpcErrorMeta(err), - pluginName, - method: trimmedMethod, - fromFallback: false - } - } - - if (hostBridge && typeof hostBridge.invokeNative === 'function') { - try { - const raw = await hostBridge.invokeNative(pluginName, trimmedMethod, params) - return unwrapDllRawPayload(raw, true) - } catch (err: unknown) { - return wrapCaughtDllError(err) - } - } - - const runtimeHost = (hostBridge ?? (globalThis as Record).ztools) as - | { dllplugin?: { call?: (plugin: string, fn: string, payload: unknown) => Promise | unknown } } - | undefined - - const callFn = runtimeHost?.dllplugin?.call - if (typeof callFn === 'function') { - try { - const raw = await callFn.call(runtimeHost?.dllplugin, pluginName, trimmedMethod, params) - return unwrapDllRawPayload(raw, false) - } catch (err: unknown) { - return wrapCaughtDllError(err) - } - } - - const ipcRes = await callHostTransport( - 'dllplugin_call', - { - plugin: pluginName, - func: trimmedMethod, - params - }, - hostBridge - ) - - if (ipcRes.ok && ipcRes.data !== undefined && ipcRes.data !== null) { - return unwrapDllRawPayload(ipcRes.data, false) - } - - const isExplicitTransportFailure = - typeof ipcRes.error === 'string' && - ipcRes.error.length > 0 && - ipcRes.error !== 'NO_WINDOW_ENV' && - !ipcRes.error.startsWith('METHOD_NOT_AVAILABLE:') - - if ( - isRealElectronHost(hostBridge) || - isRealElectronHost() || - Boolean((hostBridge as DynamicBridge)?.__isRealHost) || - isExplicitTransportFailure - ) { - const errMsg = - ipcRes.error || s.hostIpcFailed(pluginName, trimmedMethod) - return { - ok: false, - code: -1, - data: null, - message: errMsg, - error: errMsg, - ...(ipcRes.errorCode ? { errorCode: ipcRes.errorCode } : {}), - ...(ipcRes.errorDetails ? { errorDetails: ipcRes.errorDetails } : {}), - pluginName, - method: trimmedMethod, - fromFallback: false - } - } - - if (typeof offlineFallback === 'function') { - const fallbackData = await offlineFallback() - return { - ok: true, - code: 0, - data: fallbackData, - pluginName, - method: trimmedMethod, - fromFallback: true - } - } - - const unavailableMsg = s.hostUnavailable(pluginName, trimmedMethod) - return { - ok: false, - code: -1, - data: null, - message: unavailableMsg, - error: unavailableMsg, - ...(ipcRes.errorCode ? { errorCode: ipcRes.errorCode } : {}), - ...(ipcRes.errorDetails ? { errorDetails: ipcRes.errorDetails } : {}), - pluginName, - method: trimmedMethod, - fromFallback: true - } -} - -export function formatBytes(bytes: number, decimals = 1): string { - const num = Number(bytes) - if (!Number.isFinite(num) || num <= 0) return '0 B' - if (num < 1024) return `${Math.round(num)} B` - const units = ['B', 'KB', 'MB', 'GB', 'TB'] - let val = num - let idx = 0 - while (val >= 1024 && idx < units.length - 1) { - val /= 1024 - idx += 1 - } - const safeDecimals = Math.max(0, Math.floor(decimals)) - return `${val >= 100 ? val.toFixed(0) : val.toFixed(safeDecimals)} ${units[idx]}` -} - -export function joinWinPath(...segments: string[]): string { - return segments - .filter(s => typeof s === 'string' && s.trim().length > 0) - .map((s, i) => (i === 0 ? s.replace(/[\\/]+$/, '') : s.replace(/^[\\/]+|[\\/]+$/g, ''))) - .join('\\') -} - -export interface RealEnvPaths { - home: string - userProfile: string - appData: string - localAppData: string - temp: string - downloads: string - documents: string - desktop: string - pictures: string - videos: string - music: string -} - -export async function getRealEnvPaths(hostOverride?: DynamicBridge): Promise { - const [homeRaw, appData, downloads, documents, desktop, pictures, videos, music] = await Promise.all([ - getRealSystemPath('home', hostOverride), - getRealSystemPath('appData', hostOverride), - getRealSystemPath('downloads', hostOverride), - getRealSystemPath('documents', hostOverride), - getRealSystemPath('desktop', hostOverride), - getRealSystemPath('pictures', hostOverride), - getRealSystemPath('videos', hostOverride), - getRealSystemPath('music', hostOverride) - ]) - const home = homeRaw || 'C:\\Users\\Default' - const isPosix = home.startsWith('/') - const tempRes = hostOverride ? await getRealSystemPath('temp', hostOverride) : '' - if (isPosix) { - return { - home, - userProfile: home, - appData: appData || `${home}/Library/Application Support`, - localAppData: `${home}/Library/Application Support`, - temp: tempRes || '/tmp', - downloads: downloads || `${home}/Downloads`, - documents: documents || `${home}/Documents`, - desktop: desktop || `${home}/Desktop`, - pictures: pictures || `${home}/Pictures`, - videos: videos || `${home}/Videos`, - music: music || `${home}/Music` - } - } - return { - home, - userProfile: home, - appData: appData || `${home}\\AppData\\Roaming`, - localAppData: `${home}\\AppData\\Local`, - temp: tempRes || `${home}\\AppData\\Local\\Temp`, - downloads: downloads || `${home}\\Downloads`, - documents: documents || `${home}\\Documents`, - desktop: desktop || `${home}\\Desktop`, - pictures: pictures || `${home}\\Pictures`, - videos: videos || `${home}\\Videos`, - music: music || `${home}\\Music` - } -} - -export const resolveRealSpecialPaths = getRealEnvPaths - -export async function readRealDirectory( - dirPath: string, - hostOverride?: DynamicBridge -): Promise { - if (!dirPath) return [] - const tree = await scanRealDirectoryTree(dirPath, { maxFiles: 120, hostOverride }) - const entries: RealIndexedFileEntry[] = [] - for (const s of tree.subdirs) { - entries.push( - normalizeIndexedFileEntry({ - name: s.name, - path: s.path, - isDir: true, - isDirectory: true, - size: s.totalBytes, - mtime: s.mtime - }) - ) - } - for (const f of tree.files) { - entries.push(f) - } - // scanRealDirectoryTree 已在 dir: 扫描无结果时退回一级目录读取;仍为空即目录不存在 / 为空 / 无权限,如实返回空列表 - return entries -} - -export async function moveRealFilesToTrash( - paths: string[], - hostOverride?: DynamicBridge -): Promise<{ - ok: boolean - trashedCount: number - deletedCount: number - failedPaths: string[] - error?: string -}> { - let deletedCount = 0 - const failedPaths: string[] = [] - let lastError: string | undefined - for (const p of paths) { - if (!p) continue - const res = await trashRealItem(p, hostOverride) - if (res.ok) { - deletedCount += 1 - } else { - failedPaths.push(p) - if (res.error) lastError = res.error - } - } - return { - ok: deletedCount > 0 || paths.length === 0, - trashedCount: deletedCount, - deletedCount, - failedPaths, - error: lastError - } -} - -const CAPABILITY_TO_PLUGIN_MAP: Record = { - 'mover.relocateWithJunction': { plugin: 'MoverPlugin', func: 'relocateWithJunction' }, - 'mover.scanCandidates': { plugin: 'MoverPlugin', func: 'scanCandidates' }, - 'recovery.restoreFile': { plugin: 'DataRecoveryPlugin', func: 'restoreFile' }, - 'recovery.scanDeletedFiles': { plugin: 'DataRecoveryPlugin', func: 'scanDeletedFiles' }, - 'shredder.secureWipeFile': { plugin: 'ShredderPlugin', func: 'secureWipeFile' }, - 'shredder.scanCandidates': { plugin: 'ShredderPlugin', func: 'scanCandidates' }, - 'backup.createSnapshotArchive': { plugin: 'SystemBackupPlugin', func: 'createSnapshotArchive' }, - 'backup.restoreSnapshotArchive': { plugin: 'SystemBackupPlugin', func: 'restoreSnapshotArchive' }, - 'backup.scanSnapshots': { plugin: 'SystemBackupPlugin', func: 'scanSnapshots' }, - 'sqlite.execute': { plugin: 'SqlitePlugin', func: 'execute' }, - 'sqlite.query': { plugin: 'SqlitePlugin', func: 'executeQuery' }, - 'sqlite.inspectWorkspace': { plugin: 'SqlitePlugin', func: 'inspectWorkspace' } -} - -export async function invokeHostCapability( - capability: string, - params: Record = {}, - hostOverride?: DynamicBridge -): Promise> { - const normalizedMethod = capability.replace(/\./g, '_') - - // 若测试显式注入了对应 normalizedMethod 的 mock 函数,优先调用测试桩 - if (hostOverride && typeof hostOverride[normalizedMethod] === 'function') { - const mockRes = await callHostTransport(normalizedMethod, params, hostOverride) - return { - ok: mockRes.ok, - code: mockRes.ok ? 0 : -1, - message: mockRes.ok ? 'OK' : mockRes.error || ipcStrings().callFailed, - data: mockRes.data, - error: mockRes.error, - ...(!mockRes.ok && mockRes.errorCode ? { errorCode: mockRes.errorCode } : {}), - ...(!mockRes.ok && mockRes.errorDetails ? { errorDetails: mockRes.errorDetails } : {}) - } - } - - if (capability === 'system.info') { - const drives = await probeRealDiskDrives(['C', 'D', 'E', 'F'], hostOverride) - return { - ok: true, - code: 0, - message: 'OK', - data: { - storage: drives.map(d => ({ - mount: d.drive, - fs: d.drive, - size: d.totalBytes, - total: d.totalBytes, - used: d.usedBytes, - available: d.availableBytes, - free: d.availableBytes, - percent: d.usagePercent - })) - } as unknown as T - } - } - if (capability === 'filesystem.deleteItem') { - const targetPath = String(params.path || params.fullPath || '') - const tr = await trashRealItem(targetPath, hostOverride) - const s = ipcStrings() - return { - ok: tr.ok, - code: tr.ok ? 0 : -1, - message: tr.ok ? s.movedToTrash : tr.error || s.deleteFailed, - error: tr.error, - ...(!tr.ok && tr.errorCode ? { errorCode: tr.errorCode } : {}), - ...(!tr.ok && tr.errorDetails ? { errorDetails: tr.errorDetails } : {}) - } - } - if (capability === 'system.showItemInFolder') { - const targetPath = String(params.path || params.fullPath || '') - const s = ipcStrings() - if (!targetPath) { - return { ok: false, code: -1, message: s.revealFailed } - } - const res = await callHostTransport('shell_show_item_in_folder', { fullPath: targetPath }, hostOverride) - return { - ok: res.ok, - code: res.ok ? 0 : -1, - message: res.ok ? s.revealedInFolder : res.error || s.revealFailed, - ...(!res.ok && res.error ? { error: res.error } : {}), - ...(!res.ok && res.errorCode ? { errorCode: res.errorCode } : {}), - ...(!res.ok && res.errorDetails ? { errorDetails: res.errorDetails } : {}) - } - } - if (capability === 'filesystem.openItem' || capability === 'system.openUrl') { - const target = String(params.path || params.url || params.fullPath || '') - const method = capability === 'system.openUrl' ? 'shell_open_external' : 'shell_open_path' - const res = await callHostTransport( - method, - capability === 'system.openUrl' ? { url: target } : { fullPath: target }, - hostOverride - ) - const s = ipcStrings() - return { - ok: res.ok, - code: res.ok ? 0 : -1, - message: res.ok ? s.opened : res.error || s.openFailed, - data: res.data, - error: res.error, - ...(!res.ok && res.errorCode ? { errorCode: res.errorCode } : {}), - ...(!res.ok && res.errorDetails ? { errorDetails: res.errorDetails } : {}) - } - } - - const pluginMapping = CAPABILITY_TO_PLUGIN_MAP[capability] - if (pluginMapping) { - const dllRes = await invokePluginService( - pluginMapping.plugin, - pluginMapping.func, - params, - hostOverride - ) - if (dllRes.ok) return dllRes - if (hostOverride) { - const fallbackMock = await callHostTransport(normalizedMethod, params, hostOverride) - if (fallbackMock.ok) { - return { - ok: true, - code: 0, - message: 'OK', - data: fallbackMock.data - } - } - } - return dllRes - } - - const res = await callHostTransport(normalizedMethod, params, hostOverride) - return { - ok: res.ok, - code: res.ok ? 0 : -1, - message: res.ok ? 'OK' : res.error || ipcStrings().callFailed, - data: res.data, - error: res.error, - ...(!res.ok && res.errorCode ? { errorCode: res.errorCode } : {}), - ...(!res.ok && res.errorDetails ? { errorDetails: res.errorDetails } : {}) - } -} - -export async function invokePluginService( - pluginName: string, - action: string, - params: Record = {}, - hostOverride?: DynamicBridge -): Promise> { - const s = ipcStrings() - // 1. 若测试注入了专门拦截 plugin_invoke 的 mock,支持调用 - if (hostOverride && typeof hostOverride.plugin_invoke === 'function') { - const mockRes = await callHostTransport( - 'plugin_invoke', - { plugin: pluginName, action, params }, - hostOverride - ) - return { - ok: mockRes.ok, - code: mockRes.ok ? 0 : -1, - message: mockRes.ok ? 'OK' : mockRes.error || s.pluginCallNotReady, - data: mockRes.data, - error: mockRes.error, - ...(!mockRes.ok && mockRes.errorCode ? { errorCode: mockRes.errorCode } : {}), - ...(!mockRes.ok && mockRes.errorDetails ? { errorDetails: mockRes.errorDetails } : {}) - } - } - - // 2. 优先走真实 Electron IPC 的 dllplugin_call 通道 - const dllRes = await callHostTransport( - 'dllplugin_call', - { plugin: pluginName, func: action, params }, - hostOverride - ) - if (dllRes.ok) { - const inner = dllRes.data - if (inner && typeof inner === 'object' && typeof inner.error === 'string' && inner.error.length > 0 && inner.ok !== true) { - return { - ok: false, - code: -1, - message: inner.error, - error: inner.error, - ...extractIpcErrorMeta(inner) - } - } - return { - ok: true, - code: 0, - message: 'OK', - data: inner as T - } - } - - // 3. 兼容单元测试中通过 transport.call('plugin_invoke') 注入的测试桩 - if (hostOverride) { - const legacyRes = await callHostTransport( - 'plugin_invoke', - { plugin: pluginName, action, params }, - hostOverride - ) - if (legacyRes.ok) { - return { - ok: true, - code: 0, - message: 'OK', - data: legacyRes.data - } - } - } - - // 4. 兼容旧版 globalThis.ztools.dllplugin.call - const g = globalThis as DynamicBridge - if (!hostOverride && typeof g?.ztools?.dllplugin?.call === 'function') { - try { - const raw = await g.ztools.dllplugin.call(pluginName, action, params) - if (raw && typeof raw === 'object' && raw.ok === false) { - return { - ok: false, - code: -1, - message: String(raw.error || s.callFailed), - error: String(raw.error || s.callFailed), - ...extractIpcErrorMeta(raw), - ...extractIpcErrorMeta(raw.error) - } - } - const data = raw && typeof raw === 'object' && 'data' in raw ? raw.data : raw - return { ok: true, code: 0, message: 'OK', data: data as T } - } catch (err: DynamicBridge) { - return { - ok: false, - code: -1, - message: err instanceof Error ? err.message : String(err), - error: err instanceof Error ? err.message : String(err), - ...extractIpcErrorMeta(err) - } - } - } - - return { - ok: false, - code: -1, - message: dllRes.error || s.pluginCallNotReady, - error: dllRes.error || s.pluginCallNotReady, - ...(dllRes.errorCode ? { errorCode: dllRes.errorCode } : {}), - ...(dllRes.errorDetails ? { errorDetails: dllRes.errorDetails } : {}) - } -} - -const SHA256_K = new Uint32Array([ - 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, - 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, - 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, - 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, - 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, - 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, - 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, - 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2 -]) - -function rotr32(x: number, n: number): number { - return (x >>> n) | (x << (32 - n)) -} - -/** - * 标准 FIPS 180-4 SHA-256 真实字节摘要算法(返回 64 位小写 Hex) - */ -export function computeRealSha256Hex(input: string | Uint8Array): string { - const bytes = - typeof input === 'string' ? new TextEncoder().encode(input) : new Uint8Array(input || []) - const bitLen = bytes.length * 8 - const padLen = ((bytes.length + 9 + 63) & ~63) - const buf = new Uint8Array(padLen) - buf.set(bytes, 0) - buf[bytes.length] = 0x80 - const view = new DataView(buf.buffer) - view.setUint32(padLen - 8, Math.floor(bitLen / 0x100000000), false) - view.setUint32(padLen - 4, bitLen >>> 0, false) - - let h0 = 0x6a09e667 - let h1 = 0xbb67ae85 - let h2 = 0x3c6ef372 - let h3 = 0xa54ff53a - let h4 = 0x510e527f - let h5 = 0x9b05688c - let h6 = 0x1f83d9ab - let h7 = 0x5be0cd19 - - const w = new Uint32Array(64) - for (let offset = 0; offset < padLen; offset += 64) { - for (let i = 0; i < 16; i++) { - w[i] = view.getUint32(offset + i * 4, false) - } - for (let i = 16; i < 64; i++) { - const s0 = rotr32(w[i - 15], 7) ^ rotr32(w[i - 15], 18) ^ (w[i - 15] >>> 3) - const s1 = rotr32(w[i - 2], 17) ^ rotr32(w[i - 2], 19) ^ (w[i - 2] >>> 10) - w[i] = (w[i - 16] + s0 + w[i - 7] + s1) >>> 0 - } - - let a = h0 - let b = h1 - let c = h2 - let d = h3 - let e = h4 - let f = h5 - let g = h6 - let h = h7 - - for (let i = 0; i < 64; i++) { - const S1 = rotr32(e, 6) ^ rotr32(e, 11) ^ rotr32(e, 25) - const ch = (e & f) ^ (~e & g) - const temp1 = (h + S1 + ch + SHA256_K[i] + w[i]) >>> 0 - const S0 = rotr32(a, 2) ^ rotr32(a, 13) ^ rotr32(a, 22) - const maj = (a & b) ^ (a & c) ^ (b & c) - const temp2 = (S0 + maj) >>> 0 - - h = g - g = f - f = e - e = (d + temp1) >>> 0 - d = c - c = b - b = a - a = (temp1 + temp2) >>> 0 - } - - h0 = (h0 + a) >>> 0 - h1 = (h1 + b) >>> 0 - h2 = (h2 + c) >>> 0 - h3 = (h3 + d) >>> 0 - h4 = (h4 + e) >>> 0 - h5 = (h5 + f) >>> 0 - h6 = (h6 + g) >>> 0 - h7 = (h7 + h) >>> 0 - } - - return [h0, h1, h2, h3, h4, h5, h6, h7] - .map(v => (v >>> 0).toString(16).padStart(8, '0')) - .join('') -} - -/** - * 读取本地文件真实字节并计算标准 SHA-256:宿主 filesearch_sha256(只接受 path 字段)优先,Windows 上再试 FileComparePlugin。 - * 都拿不到时返回空字符串,由调用方提示失败;不再把文件按 UTF-8 文本读出来再算(二进制文件会算出错误的值)。 - */ -export async function computeRealFileSha256( - filePath: string, - hostOverride?: DynamicBridge -): Promise { - if (!filePath || !filePath.trim()) return '' - const target = filePath.trim() - - const shaRes = await callHostTransport('filesearch_sha256', { fullPath: target }, hostOverride) - if (shaRes.ok && shaRes.data) { - const hash = typeof shaRes.data === 'string' ? shaRes.data : String(shaRes.data?.sha256 || shaRes.data?.hash || '') - if (/^[0-9a-f]{64}$/i.test(hash)) return hash.toLowerCase() - } - - const dllRes = await invokePluginService('FileComparePlugin', 'computeFileSha256', { path: target }, hostOverride) - if (dllRes.ok && dllRes.data) { - const hash = typeof dllRes.data === 'string' ? dllRes.data : String(dllRes.data?.sha256 || dllRes.data?.hash || '') - if (/^[0-9a-f]{64}$/i.test(hash)) return hash.toLowerCase() - } - - return '' -} - -export async function readRealClipboardText(hostOverride?: DynamicBridge): Promise { - const res = await callHostTransport('clipboard_read_text', {}, hostOverride) - if (res.ok && res.data !== undefined && res.data !== null) { - if (typeof res.data === 'string') return res.data - if (typeof res.data?.text === 'string') return res.data.text - } - try { - if (typeof navigator !== 'undefined' && navigator.clipboard?.readText) { - return await navigator.clipboard.readText() - } - } catch { - // ignore - } - return '' -} - -export async function writeRealClipboardText(text: string, hostOverride?: DynamicBridge): Promise { - const payload = { text: String(text || '') } - const res = await callHostTransport('clipboard_copy_text', payload, hostOverride) - if (res.ok) return true - try { - if (typeof navigator !== 'undefined' && navigator.clipboard?.writeText) { - await navigator.clipboard.writeText(String(text || '')) - return true - } - } catch { - // ignore - } - return false -} - -export async function showRealToast( - title: string, - style: 'success' | 'failure' | 'info' = 'info' -): Promise { - try { - const { showToast, Toast } = await import('@ztools/declarative-ui') - await showToast({ - title, - style: - style === 'success' - ? Toast.Style.Success - : style === 'failure' - ? Toast.Style.Failure - : Toast.Style.Animated - }) - } catch { - // ignore - } -} - diff --git a/extensions/wechat-multi/tests/wechat-multi.host.test.mjs b/extensions/wechat-multi/tests/wechat-multi.host.test.mjs deleted file mode 100644 index ac39c85..0000000 --- a/extensions/wechat-multi/tests/wechat-multi.host.test.mjs +++ /dev/null @@ -1,203 +0,0 @@ -// 微信多开插件与真实 WeChatMultiPlugin.dll 8 个导出方法契约单元测试 -import test from 'node:test' -import assert from 'node:assert/strict' -import { setRuntimeLocale } from '@ztools/declarative-ui' - -setRuntimeLocale('zh-CN') -const wechat = await import('../dist/logic.js') - -test('wechat-multi 全部 8 个真实 C++ 方法契约完整对齐', async () => { - const called = [] - const host = { - dllplugin_call: async ({ plugin, func, params }) => { - assert.equal(plugin, 'WeChatMultiPlugin') - called.push({ func, params }) - switch (func) { - case 'IsWeChatInstalled': - return { - installed: true, - path: 'C:\\Program Files\\Tencent\\Weixin\\Weixin.exe', - version: 4, - versionName: '4.0.3.22' - } - case 'GetAccounts': - return { - success: true, - accounts: [ - { index: 1, wxid: 'wxid_work01', nickname: '工作号', remark: '主工作微信', avatarPath: '', running: true }, - { index: 2, wxid: 'wxid_life02', nickname: '生活号', remark: '', avatarPath: '', running: false } - ] - } - case 'GetInstances': - return { - success: true, - instances: [ - { - pid: 4321, - wxid: 'wxid_work01', - state: 'logged_in', - displayName: '主工作微信', - remark: '主工作微信', - nickname: '工作号', - avatarPath: '' - } - ] - } - case 'LaunchWeChat': - if (params.wxid === 'wxid_work01') { - return { success: true, action: 'already_running', pid: 4321, message: 'Account is already running' } - } - return { success: true, action: 'launched', pid: 8888 } - case 'SetCallback': - return { success: true, message: 'Callbacks disabled for stability' } - case 'DeleteAccount': - return { success: true } - case 'SetAccountRemark': - return { success: true } - case 'ShowInstance': - return { success: true, pid: params.pid, activated: true, message: 'Instance window activated' } - default: - throw new Error(`未预期的非白名单方法调用: ${func}`) - } - } - } - - // 1. IsWeChatInstalled - const installed = await wechat.checkWeChatInstalled(host) - assert.equal(installed.ok, true) - assert.equal(installed.installed, true) - assert.equal(installed.version, 4) - assert.equal(installed.versionName, '4.0.3.22') - - // 2. GetAccounts - const accounts = await wechat.getWeChatAccounts(host) - assert.equal(accounts.ok, true) - assert.equal(accounts.accounts.length, 2) - assert.equal(accounts.accounts[0].running, true) - - // 3. GetInstances - const instances = await wechat.getWeChatInstances(host) - assert.equal(instances.ok, true) - assert.equal(instances.instances.length, 1) - assert.equal(instances.instances[0].pid, 4321) - assert.equal(instances.instances[0].displayName, '主工作微信') - - // 4. LaunchWeChat (新建实例 & 已运行实例) - const launched = await wechat.launchWeChat('', host) - assert.equal(launched.ok, true) - assert.equal(launched.action, 'launched') - assert.equal(launched.pid, 8888) - - const alreadyRunning = await wechat.launchWeChat('wxid_work01', host) - assert.equal(alreadyRunning.ok, true) - assert.equal(alreadyRunning.action, 'already_running') - assert.equal(alreadyRunning.pid, 4321) - assert.match(alreadyRunning.message, /已在运行中/) - - // 5. SetCallback - const cbRes = await wechat.setWeChatCallback({}, host) - assert.equal(cbRes.ok, true) - - // 6. SetAccountRemark - const remarkRes = await wechat.setWeChatAccountRemark(2, '测试备注', host) - assert.equal(remarkRes.ok, true) - - // 7. DeleteAccount - const delRes = await wechat.deleteWeChatAccount({ accountIndex: 2 }, host) - assert.equal(delRes.ok, true) - - // 8. ShowInstance(已运行实例激活) - const showRes = await wechat.showWeChatInstance(4321, host) - assert.equal(showRes.ok, true) - assert.equal(showRes.activated, true) - assert.match(showRes.message, /已激活微信窗口/) - - // 确认全部 8 个真实方法全部覆盖且无越界方法名 - const calledSet = new Set(called.map((c) => c.func)) - for (const fn of wechat.WECHAT_MULTI_DLL_FUNCTIONS) { - assert.ok(calledSet.has(fn), `缺少对真实导出方法 ${fn} 的契约校验`) - } - assert.equal(calledSet.size, 8) -}) - -test('wechat-multi: 微信未安装时如实提示,不返回假路径或假进程', async () => { - const host = { - dllplugin_call: async ({ func }) => { - if (func === 'IsWeChatInstalled') return { installed: false } - if (func === 'GetInstances') return { success: true, instances: [] } - if (func === 'GetAccounts') return { success: true, accounts: [] } - if (func === 'LaunchWeChat') { - return { success: false, errorCode: 'FILE_NOT_FOUND', launchErrorCode: -1, error: 'WeChat installation not found' } - } - throw new Error(`unexpected ${func}`) - } - } - - const snap = await wechat.fetchWeChatMultiSnapshot(host) - assert.equal(snap.ok, true) - assert.equal(snap.installed, false) - assert.equal(snap.installPath, '') - assert.deepEqual(snap.instances, []) - - const launch = await wechat.launchWeChat('', host) - assert.equal(launch.ok, false) - assert.equal(launch.errorCode, 'WECHAT_NOT_FOUND') - assert.match(launch.message, /未检测到本地微信/) -}) - -test('wechat-multi: 未知微信版本互斥体未在白名单内时如实报错中止', async () => { - const host = { - dllplugin_call: async ({ func }) => { - assert.equal(func, 'LaunchWeChat') - return { - success: false, - errorCode: 'UNSUPPORTED_OPTION', - launchErrorCode: -8, - error: 'Unsupported WeChat version: instance identity mutex not in whitelist' - } - } - } - - const res = await wechat.launchWeChat('', host) - assert.equal(res.ok, false) - assert.equal(res.errorCode, 'UNSUPPORTED_WECHAT_VERSION') - assert.match(res.message, /白名单/) -}) - -test('wechat-multi: 目标微信以管理员权限运行时给出明确最小权限提示', async () => { - const host = { - dllplugin_call: async ({ func }) => { - assert.equal(func, 'LaunchWeChat') - return { - success: false, - errorCode: 'PERMISSION_DENIED', - launchErrorCode: -9, - error: 'Cannot access elevated WeChat process under standard user privileges' - } - } - } - - const res = await wechat.launchWeChat('', host) - assert.equal(res.ok, false) - assert.equal(res.errorCode, 'PERMISSION_DENIED') - assert.match(res.message, /管理员权限/) -}) - -test('wechat-multi: 不在客户端环境与双语热切换均表现正确', async () => { - try { - setRuntimeLocale('zh-CN') - const snapZh = await wechat.fetchWeChatMultiSnapshot() - assert.equal(snapZh.ok, false) - assert.equal(snapZh.error, wechat.getHostRequiredMessage()) - assert.match(wechat.getLaunchLimitNote(), /不承诺绕过微信协议/) - - setRuntimeLocale('en-US') - const snapEn = await wechat.fetchWeChatMultiSnapshot() - assert.equal(snapEn.ok, false) - assert.doesNotMatch(snapEn.error, /[\u4e00-\u9fa5]/) - assert.doesNotMatch(wechat.getLaunchLimitNote(), /[\u4e00-\u9fa5]/) - assert.match(wechat.getLaunchLimitNote(), /does not promise bypassing WeChat protocol/i) - } finally { - setRuntimeLocale('zh-CN') - } -}) diff --git a/extensions/wechat-multi/tests/wechat-multi.ui.test.mjs b/extensions/wechat-multi/tests/wechat-multi.ui.test.mjs deleted file mode 100644 index 3b40a3f..0000000 --- a/extensions/wechat-multi/tests/wechat-multi.ui.test.mjs +++ /dev/null @@ -1,112 +0,0 @@ -import test from 'node:test' -import assert from 'node:assert/strict' -import { Toast } from '@ztools/declarative-ui' -import { createHost, mount, tick } from '../../shared/test-harness.mjs' -import WechatMultiCommand from '../dist/index.js' - -const host = createHost() -const rejections = [] -process.on('unhandledRejection', (reason) => rejections.push(reason)) - -test.beforeEach(() => { - host.reset() - rejections.length = 0 -}) - -function installWechatHost({ installed = true, instances = [], accounts = [], launchRes, showRes } = {}) { - host.ipc.dllplugin_call = async ({ plugin, func, params }) => { - assert.equal(plugin, 'WeChatMultiPlugin') - if (func === 'IsWeChatInstalled') { - return installed - ? { installed: true, path: 'C:\\Program Files\\Tencent\\Weixin\\Weixin.exe', version: 4, versionName: '4.0.3.22' } - : { installed: false } - } - if (func === 'GetInstances') { - return { success: true, instances } - } - if (func === 'GetAccounts') { - return { success: true, accounts } - } - if (func === 'LaunchWeChat') { - if (typeof launchRes === 'function') return launchRes(params) - return launchRes || { success: true, action: 'launched', pid: 5555 } - } - if (func === 'ShowInstance') { - return showRes || { success: true, pid: params.pid, activated: true } - } - if (func === 'DeleteAccount') { - return { success: true } - } - throw new Error(`未模拟方法 ${func}`) - } -} - -test('wechat-multi UI: 展示运行实例与激活窗口操作,严禁出现结束微信进程入口', async () => { - installWechatHost({ - instances: [ - { pid: 4321, wxid: 'wxid_work01', state: 'logged_in', displayName: '工作微信号', remark: '工作微信号', nickname: '' } - ], - accounts: [ - { index: 1, wxid: 'wxid_work01', nickname: '', remark: '工作微信号', avatarPath: '', running: true } - ] - }) - const view = await mount(WechatMultiCommand, host) - await tick(20) - - const text = view.text() - assert.equal(/结束进程|杀掉|强制关闭/.test(text), false) - assert.match(view.tree().props.filterBar.summaryText, /微信 4\.0\.3\.22 · 运行实例 1 个 · 已记录账号 1 个/) - - const row = view.item('wx-proc-4321') - assert.equal(row.props.title, '工作微信号') - await view.run(row, '切换到此窗口') - await tick(10) - assert.equal(host.lastToast().style, Toast.Style.Success) - assert.match(host.lastToast().title, /已激活微信窗口 \(PID 4321\)/) - view.unmount() -}) - -test('wechat-multi UI: 微信未安装时清晰提示并阻止无效启动', async () => { - installWechatHost({ installed: false }) - const view = await mount(WechatMultiCommand, host) - await tick(20) - - assert.match(view.tree().props.filterBar.summaryText, /未检测到本地微信安装/) - await view.run(view.item('wx-launch'), '启动新的微信实例') - await tick(10) - assert.equal(host.lastToast().style, Toast.Style.Failure) - assert.match(host.lastToast().message, /未检测到本地微信/) - assert.equal(host.ipcCalls.some(([m, p]) => m === 'dllplugin_call' && p.func === 'LaunchWeChat'), false) - view.unmount() -}) - -test('wechat-multi UI: 启动已运行账号自动激活已有实例窗口;未知版本报错清晰提示', async () => { - installWechatHost({ - installed: true, - instances: [{ pid: 4321, wxid: 'wxid_work01', state: 'logged_in', displayName: '主号', remark: '主号', nickname: '' }], - accounts: [{ index: 1, wxid: 'wxid_work01', nickname: '', remark: '主号', avatarPath: '', running: true }], - launchRes: (params) => { - if (params.wxid === 'wxid_work01') { - return { success: true, action: 'already_running', pid: 4321 } - } - return { success: false, errorCode: 'UNSUPPORTED_OPTION', launchErrorCode: -8, error: 'Unsupported WeChat version' } - } - }) - - const view = await mount(WechatMultiCommand, host) - await tick(20) - - // 点击已运行账号应触发 LaunchWeChat -> ShowInstance - await view.run(view.item('wx-acc-1'), '启动此账号') - await tick(20) - assert.equal(host.ipcCalls.some(([m, p]) => m === 'dllplugin_call' && p.func === 'ShowInstance' && p.params.pid === 4321), true) - assert.equal(host.lastToast().style, Toast.Style.Success) - - // 点击新建多开遇到未知版本互斥体应清晰报错 - await view.run(view.item('wx-launch'), '启动新的微信实例') - await tick(20) - assert.equal(host.lastToast().style, Toast.Style.Failure) - assert.match(host.lastToast().message, /白名单/) - assert.deepEqual(rejections, []) - view.unmount() -}) diff --git a/extensions/wechat-multi/tsconfig.json b/extensions/wechat-multi/tsconfig.json deleted file mode 100644 index 1346df8..0000000 --- a/extensions/wechat-multi/tsconfig.json +++ /dev/null @@ -1,19 +0,0 @@ -{ - "compilerOptions": { - "target": "ES2022", - "module": "CommonJS", - "moduleResolution": "node", - "strict": true, - "esModuleInterop": true, - "skipLibCheck": true, - "forceConsistentCasingInFileNames": true, - "outDir": "dist", - "rootDir": "src", - "typeRoots": [ - "../../frontend/node_modules/@types" - ] - }, - "include": [ - "src/**/*" - ] -} diff --git a/packages/ztools-plugins-spec/src/validator.js b/packages/ztools-plugins-spec/src/validator.js index 704a6c7..f15d629 100644 --- a/packages/ztools-plugins-spec/src/validator.js +++ b/packages/ztools-plugins-spec/src/validator.js @@ -1004,11 +1004,33 @@ export function validateCatalogPluginItem(item) { } /** - * 校验全量商店目录清单 (Store Catalog Index, 即 plugins.json) + * 判断插件清单或目录条目是否声明了原生组件(nativeComponents 非空或声明了 dllloader)。 + * 全仓导出隔离、PR 校验、构建分流与部署闸门均以此函数为唯一判定准绳(SSOT)。 + * @param {object} manifest - 插件清单或目录条目 + * @returns {boolean} + */ +export function isNativePluginManifest(manifest) { + if (!manifest || typeof manifest !== 'object' || Array.isArray(manifest)) { + return false + } + if (Array.isArray(manifest.nativeComponents) && manifest.nativeComponents.length > 0) { + return true + } + if (typeof manifest.dllloader === 'string' && manifest.dllloader.trim().length > 0) { + return true + } + return false +} + +/** + * 校验全量商店目录清单 (Store Catalog Index, 即 plugins.json / catalog.json / native-catalog.json) * @param {object} catalog - 目录对象 + * @param {{ channel?: 'public' | 'native' }} [options] - 可选分发通道约束: + * - 'public'(公开纯声明式目录):禁止非下架条目声明 nativeComponents 或 dllloader + * - 'native'(原生签名目录):要求非下架条目必须声明 nativeComponents 且存在 dllloader * @returns {{ valid: boolean, errors: string[], totalValid: number, revokedCount: number }} */ -export function validateStoreCatalog(catalog) { +export function validateStoreCatalog(catalog, options = {}) { const errors = [] if (!catalog || typeof catalog !== 'object' || Array.isArray(catalog)) { return { valid: false, errors: ['Catalog must be a non-null object'], totalValid: 0, revokedCount: 0 } @@ -1019,14 +1041,29 @@ export function validateStoreCatalog(catalog) { return { valid: false, errors, totalValid: 0, revokedCount: 0 } } + const channel = options?.channel === 'public' || options?.channel === 'native' ? options.channel : null let totalValid = 0 let revokedCount = 0 const seenIds = new Set() for (const [idx, item] of catalog.plugins.entries()) { const itemValidation = validateCatalogPluginItem(item) - if (!itemValidation.valid) { - errors.push(`plugins[${idx}] validation failed: ${itemValidation.errors.join('; ')}`) + const itemErrors = [...itemValidation.errors] + if (channel && item && typeof item === 'object' && !Array.isArray(item) && item.revoked !== true) { + const isNative = isNativePluginManifest(item) + if (channel === 'public' && isNative) { + itemErrors.push(`public catalog entry "${item.id || idx}" must not declare nativeComponents or dllloader`) + } else if (channel === 'native') { + if (!Array.isArray(item.nativeComponents) || item.nativeComponents.length === 0) { + itemErrors.push(`native catalog entry "${item.id || idx}" must declare non-empty nativeComponents`) + } + if (typeof item.dllloader !== 'string' || item.dllloader.trim().length === 0) { + itemErrors.push(`native catalog entry "${item.id || idx}" must declare dllloader`) + } + } + } + if (itemErrors.length > 0) { + errors.push(`plugins[${idx}] validation failed: ${itemErrors.join('; ')}`) } else { totalValid++ if (item.revoked) { diff --git a/scripts/build-plugins-release.mjs b/scripts/build-plugins-release.mjs index 07f6413..ec88401 100644 --- a/scripts/build-plugins-release.mjs +++ b/scripts/build-plugins-release.mjs @@ -25,6 +25,7 @@ import { scanPluginSecurity } from './scan-plugin-security.mjs' import { getManifestPlatforms, validateStoreCatalog, + isNativePluginManifest, OFFICIAL_PLUGIN_IDS, inspectScreenshotFile, SCREENSHOT_PATH_REGEX, @@ -586,6 +587,7 @@ export async function buildPluginsRelease(options = {}) { try { const manifest = JSON.parse(fs.readFileSync(path.join(entry.dir, 'plugin.json'), 'utf8')) if (manifest.revoked === true || manifest.draft === true) continue + if (isNativePluginManifest(manifest)) continue } catch { continue } @@ -616,6 +618,7 @@ export async function buildPluginsRelease(options = {}) { const publishedPackages = [] const catalogList = [] const draftIds = [] + const nativeSkippedIds = [] let rejectedCount = 0 for (const entry of pluginEntries) { @@ -676,6 +679,15 @@ export async function buildPluginsRelease(options = {}) { continue } + // 原生组件隔离:声明了 nativeComponents 或 dllloader 的插件必须由独立原生签名通道打包二进制与信任签名并写入原生目录, + // 公开纯声明式构建通道自动跳过,严防把不含原生二进制和签名的空壳包推上公开 catalog.json。 + if (isNativePluginManifest(manifest)) { + const nativeCount = Array.isArray(manifest.nativeComponents) ? manifest.nativeComponents.length : 0 + console.warn(`[原生组件跳过] [${pluginId}] 声明了原生能力(nativeComponents=${nativeCount}${manifest.dllloader ? `, dllloader=${manifest.dllloader}` : ''}),公开声明式通道自动跳过(须由原生签名通道独立发布)`) + nativeSkippedIds.push(manifest.id || pluginId) + continue + } + // 1. 安全 AST 扫描与 Schema 门禁 let scanResult = null if (!skipScan) { @@ -812,7 +824,7 @@ export async function buildPluginsRelease(options = {}) { targets: manifest.targets, // 便于客户端与市场直接展示:'windows' / 'macos' 的子集 platforms: getManifestPlatforms(manifest), - nativeComponents: Array.isArray(manifest.nativeComponents) ? manifest.nativeComponents : [], + nativeComponents: [], // 新客户端应直接依据 is_official 布尔值按当前语言本地化渲染官方徽章; // official_badge 仅保留用于向后兼容老客户端,不应被新客户端作为文案真源依赖 is_official: isOfficial, @@ -853,8 +865,8 @@ export async function buildPluginsRelease(options = {}) { plugins: catalogList } - // 写出前整体校验:插件 ID 重复、版本号或下载信息不合法时不生成目录 - const catalogCheck = validateStoreCatalog(pluginsIndex) + // 写出前整体校验:插件 ID 重复、版本号或下载信息不合法、或混入原生插件时不生成公开目录 + const catalogCheck = validateStoreCatalog(pluginsIndex, { channel: 'public' }) if (!catalogCheck.valid) { throw new Error(`插件目录校验失败,已停止生成:\n - ${catalogCheck.errors.join('\n - ')}`) } @@ -867,7 +879,7 @@ export async function buildPluginsRelease(options = {}) { console.log(`\n============================================================`) console.log(`📄 静态全网索引 plugins.json & catalog.json 已生成: ${indexPath}`) - console.log(`📊 统计: 共发现 ${pluginEntries.length} 个插件,成功打包 ${catalogList.length} 个,拦截拒绝 ${rejectedCount} 个,草稿未发布 ${draftIds.length} 个`) + console.log(`📊 统计: 共发现 ${pluginEntries.length} 个插件,成功打包 ${catalogList.length} 个,拦截拒绝 ${rejectedCount} 个,草稿未发布 ${draftIds.length} 个,原生通道跳过 ${nativeSkippedIds.length} 个`) console.log(`============================================================\n`) return { @@ -876,6 +888,7 @@ export async function buildPluginsRelease(options = {}) { passedCount: catalogList.length, rejectedCount, draftIds, + nativeSkippedIds, pluginsIndex, publishedPackages } diff --git a/scripts/deploy-plugins-storage.mjs b/scripts/deploy-plugins-storage.mjs index 79a9923..6e6528e 100644 --- a/scripts/deploy-plugins-storage.mjs +++ b/scripts/deploy-plugins-storage.mjs @@ -16,9 +16,11 @@ import fs from 'node:fs' import path from 'node:path' import crypto from 'node:crypto' +import zlib from 'node:zlib' import https from 'node:https' import http from 'node:http' import { fileURLToPath } from 'node:url' +import { isNativePluginManifest } from '../packages/ztools-plugins-spec/src/validator.js' const __dirname = path.dirname(fileURLToPath(import.meta.url)) const rootDir = path.resolve(__dirname, '..') @@ -633,6 +635,173 @@ function isIndexFile(relPath) { return relPath.toLowerCase().endsWith('.json') } +/** + * 零依赖解析 ZIP 中央目录,用于部署前快速抽检安装包内容(不落盘解压)。 + * 非合法 ZIP 返回 { valid: false, entries: Map }。 + */ +export function inspectZipEntries(zipBuffer) { + const entries = new Map() + if (!Buffer.isBuffer(zipBuffer) || zipBuffer.length < 22) { + return { valid: false, entries } + } + let eocdOffset = -1 + const minOffset = Math.max(0, zipBuffer.length - 65557) + for (let i = zipBuffer.length - 22; i >= minOffset; i--) { + if (zipBuffer.readUInt32LE(i) === 0x06054b50) { + eocdOffset = i + break + } + } + if (eocdOffset === -1) { + return { valid: false, entries } + } + const totalEntries = zipBuffer.readUInt16LE(eocdOffset + 10) + let cdOffset = zipBuffer.readUInt32LE(eocdOffset + 16) + for (let i = 0; i < totalEntries; i++) { + if (cdOffset + 46 > zipBuffer.length || zipBuffer.readUInt32LE(cdOffset) !== 0x02014b50) { + return { valid: false, entries } + } + const compressionMethod = zipBuffer.readUInt16LE(cdOffset + 10) + const compressedSize = zipBuffer.readUInt32LE(cdOffset + 20) + const nameLen = zipBuffer.readUInt16LE(cdOffset + 28) + const extraLen = zipBuffer.readUInt16LE(cdOffset + 30) + const commentLen = zipBuffer.readUInt16LE(cdOffset + 32) + const localHeaderOffset = zipBuffer.readUInt32LE(cdOffset + 42) + if (cdOffset + 46 + nameLen > zipBuffer.length) { + return { valid: false, entries } + } + const name = zipBuffer.subarray(cdOffset + 46, cdOffset + 46 + nameLen).toString('utf8').replaceAll('\\', '/') + entries.set(name, { name, compressionMethod, compressedSize, localHeaderOffset }) + cdOffset += 46 + nameLen + extraLen + commentLen + } + return { valid: true, entries } +} + +function readZipEntryUtf8(zipBuffer, meta) { + if (!meta || meta.localHeaderOffset + 30 > zipBuffer.length) return null + if (zipBuffer.readUInt32LE(meta.localHeaderOffset) !== 0x04034b50) return null + const localNameLen = zipBuffer.readUInt16LE(meta.localHeaderOffset + 26) + const localExtraLen = zipBuffer.readUInt16LE(meta.localHeaderOffset + 28) + const dataStart = meta.localHeaderOffset + 30 + localNameLen + localExtraLen + if (dataStart + meta.compressedSize > zipBuffer.length) return null + const slice = zipBuffer.subarray(dataStart, dataStart + meta.compressedSize) + if (meta.compressionMethod === 0) return slice.toString('utf8') + if (meta.compressionMethod === 8) return zlib.inflateRawSync(slice).toString('utf8') + return null +} + +/** + * 部署前终极通道防混与防空壳预检(零上传拦截,演练与正式模式均强制执行): + * 1. 公开目录(catalog.json / plugins.json):严禁混入声明原生组件的活跃插件或含原生声明/签名/DLL 的安装包; + * 2. 原生目录(native-catalog.json):活跃插件必须声明原生组件,且对应本地待上传 ZIP 必须包含 + * native-trust.json、native-trust.sig 以及清单声明的全部主 DLL 与 payload 二进制,彻底封死空壳包上传。 + */ +export function validateDeployCatalogChannel({ catalog, catalogFile, packages = [], cdnBaseUrl, prefix = '' }) { + const isNativeCatalog = catalogFile === 'native-catalog.json' + const isPublicCatalog = catalogFile === 'catalog.json' || catalogFile === 'plugins.json' + if (!isNativeCatalog && !isPublicCatalog) return + + const cleanPrefix = normalizePrefix(prefix) + const localZipByUrl = new Map() + for (const file of packages) { + if (!file.relPath.toLowerCase().endsWith('.zip')) continue + const objectKey = cleanPrefix ? `${cleanPrefix}/${file.relPath}` : file.relPath + localZipByUrl.set(`${cdnBaseUrl}/${objectKey}`, file) + } + + const readFileBuffer = (file) => (Buffer.isBuffer(file.buffer) ? file.buffer : fs.readFileSync(file.fullPath)) + const entries = catalog ? catalogEntries(catalog) : [] + + if (isPublicCatalog) { + const violations = [] + for (const item of entries) { + if (!item || typeof item !== 'object' || item.revoked === true) continue + if (isNativePluginManifest(item)) { + violations.push(`目录条目 ${item.id || item.pluginId || ''} 声明了原生组件(nativeComponents / dllloader)`) + } + } + for (const file of packages) { + if (!file.relPath.toLowerCase().endsWith('.zip')) continue + const buf = readFileBuffer(file) + const inspected = inspectZipEntries(buf) + if (!inspected.valid) continue + const names = [...inspected.entries.keys()] + if (names.includes('native-trust.json') || names.includes('native-trust.sig')) { + violations.push(`安装包 ${file.relPath} 包含原生信任签名文件,不能走公开声明式目录`) + } + if (inspected.entries.has('plugin.json')) { + try { + const manifestText = readZipEntryUtf8(buf, inspected.entries.get('plugin.json')) + const manifest = manifestText ? JSON.parse(manifestText) : null + if (manifest && manifest.revoked !== true && isNativePluginManifest(manifest)) { + violations.push(`安装包 ${file.relPath} 内的 plugin.json 声明了原生组件,禁止上传至公开目录 ${catalogFile}`) + } + } catch (err) { + violations.push(`安装包 ${file.relPath} 内的 plugin.json 解析失败: ${err.message}`) + } + } + } + if (violations.length > 0) { + throw new Error( + `公开目录 ${catalogFile} 渠道安全校验失败,已中止且未上传任何文件(原生插件须走原生签名通道发布至 native-catalog.json):\n - ${violations.join('\n - ')}` + ) + } + return + } + + // 原生目录 native-catalog.json 强制校验:禁止纯声明式插件混入,且待上传 ZIP 必须包含签名与全部声明二进制 + const violations = [] + for (const item of entries) { + if (!item || typeof item !== 'object' || item.revoked === true) continue + const id = item.id || item.pluginId || '' + if (!isNativePluginManifest(item)) { + violations.push(`目录条目 ${id} 未声明 nativeComponents 或 dllloader,禁止将纯声明式插件写入 native-catalog.json`) + continue + } + const downloadUrl = String(item.downloadUrl || '').trim() + const zipFile = downloadUrl ? localZipByUrl.get(downloadUrl) : null + if (!zipFile) continue + + const buf = readFileBuffer(zipFile) + const inspected = inspectZipEntries(buf) + if (!inspected.valid) { + violations.push(`原生安装包 ${zipFile.relPath} 不是有效的 ZIP 压缩包,拒绝上传`) + continue + } + if (!inspected.entries.has('native-trust.json') || !inspected.entries.has('native-trust.sig')) { + violations.push(`原生安装包 ${zipFile.relPath} 缺少 native-trust.json 或 native-trust.sig 信任签名文件,拒绝上传空壳包`) + } + const requiredPaths = new Set() + if (typeof item.dllloader === 'string' && item.dllloader.trim()) { + requiredPaths.add(item.dllloader.trim().replaceAll('\\', '/')) + } + if (Array.isArray(item.nativeComponents)) { + for (const comp of item.nativeComponents) { + if (typeof comp?.entry === 'string' && comp.entry.trim()) { + requiredPaths.add(comp.entry.trim().replaceAll('\\', '/')) + } + if (Array.isArray(comp?.payloadFiles)) { + for (const pf of comp.payloadFiles) { + if (typeof pf?.entry === 'string' && pf.entry.trim()) { + requiredPaths.add(pf.entry.trim().replaceAll('\\', '/')) + } + } + } + } + } + for (const reqPath of requiredPaths) { + if (!inspected.entries.has(reqPath)) { + violations.push(`原生安装包 ${zipFile.relPath} 缺少声明的原生二进制文件 ${reqPath},拒绝上传空壳包`) + } + } + } + if (violations.length > 0) { + throw new Error( + `原生目录 ${catalogFile} 防空壳安全校验失败,已中止且未上传任何文件:\n - ${violations.join('\n - ')}` + ) + } +} + /** * 核心部署流程 */ @@ -708,6 +877,15 @@ export async function deployPluginsStorage(options = {}) { const nextCatalogFile = indexes.find((f) => f.relPath === catalogFile) const nextCatalog = nextCatalogFile ? JSON.parse(fs.readFileSync(nextCatalogFile.fullPath, 'utf8')) : null + // 渠道防混与防空壳终极预检(演练与正式模式均强制执行,任一不通过零上传) + validateDeployCatalogChannel({ + catalog: nextCatalog, + catalogFile, + packages, + cdnBaseUrl, + prefix + }) + // 防误覆盖保护:上传 native-catalog.json 且线上存在更多插件时,禁止在未显式声明合并或替换的情况下直接整份覆盖 if (!mergeRemoteCatalog && !replaceCatalog && catalogFile === 'native-catalog.json' && previousCatalog && nextCatalog) { const nextIds = new Set(catalogEntries(nextCatalog).map(normalizeCatalogPluginId).filter(Boolean)) diff --git a/scripts/verify-changed-plugins.mjs b/scripts/verify-changed-plugins.mjs index dcc5c68..8a3f59e 100644 --- a/scripts/verify-changed-plugins.mjs +++ b/scripts/verify-changed-plugins.mjs @@ -28,7 +28,7 @@ import path from 'node:path' import { fileURLToPath } from 'node:url' import { scanPluginSecurity } from './scan-plugin-security.mjs' import { checkSinglePluginI18n } from './check-i18n-public.mjs' -import { describePlatforms, getManifestPlatforms } from '../packages/ztools-plugins-spec/src/validator.js' +import { describePlatforms, getManifestPlatforms, isNativePluginManifest } from '../packages/ztools-plugins-spec/src/validator.js' const SHARED_DIR = 'shared' const SKIP_DIRS = new Set(['node_modules', '.git', 'dist', SHARED_DIR, 'scripts', 'packages']) @@ -180,7 +180,25 @@ export async function verifyChangedPlugins({ root = process.cwd(), base = null, } for (const dir of deleted) { - errorOf(dir).errors.push('不能直接删除插件目录:已安装的用户收不到下架通知。请保留目录,在 plugin.json 写 "revoked": true 和 "revokedReason"') + // 若被删除目录在基线分支中本身属于声明了 nativeComponents / dllloader 的原生插件, + // 说明是清理历史误入公开仓的原生残留(由独立原生签名通道发布),允许删除并给出说明; + // 其余纯声明式插件严禁直接删除,须通过 revoked: true 保留下架通知。 + let wasNativeInBase = false + if (base) { + const prevRaw = gitShow(root, base, `${dir}/plugin.json`) + if (prevRaw) { + try { + wasNativeInBase = isNativePluginManifest(JSON.parse(prevRaw)) + } catch { + wasNativeInBase = false + } + } + } + if (wasNativeInBase) { + errorOf(dir).notes.push('已清理误入公开仓的原生插件目录(由原生签名通道独立发布)') + } else { + errorOf(dir).errors.push('不能直接删除插件目录:已安装的用户收不到下架通知。请保留目录,在 plugin.json 写 "revoked": true 和 "revokedReason"') + } } const buildScript = findBuildScript(root, pluginsRel) @@ -219,6 +237,15 @@ export async function verifyChangedPlugins({ root = process.cwd(), base = null, continue } + // 公开插件仓库(extensions/)严禁合入声明原生组件的活跃插件:公开仓不含原生二进制与签名私钥,发包必为空壳 + if (isNativePluginManifest(manifest)) { + if (pluginsRel === 'extensions') { + r.errors.push('公开插件仓库不支持声明 nativeComponents 或 dllloader 的原生插件,请勿提交到公开仓库(官方原生插件走独立签名发布通道)') + } else { + r.notes.push('原生插件(须由原生签名通道独立发布)') + } + } + // 先从源码编译:清单校验要求入口文件存在 if (fs.existsSync(path.join(root, dir, 'tsconfig.json'))) { if (!buildScript) {