From 3b80dab095dce68d4607ad68fcf7e69d2f41ea30 Mon Sep 17 00:00:00 2001 From: wangtao <40267153+GIWTO@users.noreply.github.com> Date: Fri, 27 Nov 2026 16:45:45 +0800 Subject: [PATCH] =?UTF-8?q?Add=20plugin=20=E5=BF=AB=E9=80=9F=E5=AF=86?= =?UTF-8?q?=E7=A0=81=E5=A1=AB=E5=85=85=20v0.0.1?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - feat: initial release v1.0.0 - feat: add pack script for zpx and zip - fix: use ztools official hideMainWindowPasteText and hideMainWindowTypeString for auto-fill - feat: adapt for Linux and macOS, update author to wangtao - fix: load native addon in preload with 300ms window focus delay and remove focus-stealing notification - docs: add user manual and super panel middle-click guide to README, MANUAL.md and UI modal - chore: prepare v0.0.1 for ZTools plugin market release --- plugins/ztools-quick-pwd/.gitignore | 4 + plugins/ztools-quick-pwd/CHANGELOG.md | 11 + plugins/ztools-quick-pwd/MANUAL.md | 87 + plugins/ztools-quick-pwd/README.md | 134 ++ plugins/ztools-quick-pwd/index.css | 1047 +++++++++++ plugins/ztools-quick-pwd/index.html | 389 ++++ plugins/ztools-quick-pwd/index.js | 1615 +++++++++++++++++ plugins/ztools-quick-pwd/libs/crypto.js | 89 + plugins/ztools-quick-pwd/libs/mouse-hook.js | 193 ++ plugins/ztools-quick-pwd/libs/store.js | 137 ++ plugins/ztools-quick-pwd/logo.png | Bin 0 -> 1318 bytes plugins/ztools-quick-pwd/plugin.json | 29 + plugins/ztools-quick-pwd/preload.js | 1370 ++++++++++++++ .../scripts/mid-btn-watch.ps1 | 52 + plugins/ztools-quick-pwd/scripts/pack.js | 110 ++ 15 files changed, 5267 insertions(+) create mode 100644 plugins/ztools-quick-pwd/.gitignore create mode 100644 plugins/ztools-quick-pwd/CHANGELOG.md create mode 100644 plugins/ztools-quick-pwd/MANUAL.md create mode 100644 plugins/ztools-quick-pwd/README.md create mode 100644 plugins/ztools-quick-pwd/index.css create mode 100644 plugins/ztools-quick-pwd/index.html create mode 100644 plugins/ztools-quick-pwd/index.js create mode 100644 plugins/ztools-quick-pwd/libs/crypto.js create mode 100644 plugins/ztools-quick-pwd/libs/mouse-hook.js create mode 100644 plugins/ztools-quick-pwd/libs/store.js create mode 100644 plugins/ztools-quick-pwd/logo.png create mode 100644 plugins/ztools-quick-pwd/plugin.json create mode 100644 plugins/ztools-quick-pwd/preload.js create mode 100644 plugins/ztools-quick-pwd/scripts/mid-btn-watch.ps1 create mode 100644 plugins/ztools-quick-pwd/scripts/pack.js diff --git a/plugins/ztools-quick-pwd/.gitignore b/plugins/ztools-quick-pwd/.gitignore new file mode 100644 index 000000000..2c5594d66 --- /dev/null +++ b/plugins/ztools-quick-pwd/.gitignore @@ -0,0 +1,4 @@ +*.zpx +*.zip +.DS_Store +node_modules/ diff --git a/plugins/ztools-quick-pwd/CHANGELOG.md b/plugins/ztools-quick-pwd/CHANGELOG.md new file mode 100644 index 000000000..0d21d0eff --- /dev/null +++ b/plugins/ztools-quick-pwd/CHANGELOG.md @@ -0,0 +1,11 @@ +# 更新日志 (CHANGELOG) + +## 0.0.1 - 2026-11-27 + +### 新增功能 +- **初次发布至 ZTools 插件市场**:提供本地 AES-256-GCM 加密密码存储与极速自动填充能力,纯本地零依赖运行。 +- **高强度加密与双模式解锁**:采用 PBKDF2 (SHA-256, 100,000 次迭代) + AES-256-GCM 加密保险库;支持主密码 PIN 保护、修改主密码全库重加密、空闲自动锁定,并支持免密模式开关及初始化跳过入口。 +- **极简快捷选密与三键分离填充**:支持配合 ZTools 超级面板(长按鼠标中键)或快捷指令呼出;支持空格多词高亮检索、条目置顶与使用频率排序,提供「账号+密码」「账号」「密码」三键分离填充及 `Enter` / `Shift+Enter` / `Alt+Enter` / `Alt+1~9` / `Ctrl+C` 全键盘操作。 +- **可靠保序回填与剪贴板防护**:支持快速粘贴与模拟键盘逐字键入双模式,单通道剪贴板落盘校验与可配置 Tab 切换等待,杜绝双框填反;自动定时智能清理剪贴板敏感密码残留。 +- **完整管理台与数据备份**:内置 16 位随机强密码生成器与密码强度评估、备注字段、深浅色自适应主题、独立桌面窗口模式及加密备份导入导出(`.json`)。 +- **跨平台支持**:全面适配 Windows、macOS 与 Linux。 diff --git a/plugins/ztools-quick-pwd/MANUAL.md b/plugins/ztools-quick-pwd/MANUAL.md new file mode 100644 index 000000000..1745ad484 --- /dev/null +++ b/plugins/ztools-quick-pwd/MANUAL.md @@ -0,0 +1,87 @@ +# 快速密码填充插件使用手册 +> **通过长按鼠标中键呼起超级面板,实现就地极速自动填密** + +--- + +## 🎯 核心使用理念 + +传统密码工具通常需要: +`切换窗口 ➔ 搜索密码 ➔ 复制 ➔ 切回目标窗口 ➔ 粘贴`。 + +本插件配合 ZTools 超级面板后,操作路径缩短为极致的 **“就地触发,无感回填”**: +``` +光标在账号框(双填) 或 密码框(仅密码) ➔ 就地长按中键 0.5 秒 ➔ 点「填密码」 ➔ 选密回车 ➔ 严格保序自动填入并隐去 +``` + +--- + +## ⚙️ 第一部分:首次使用配置指南(仅需一次) + +### 步骤 1:在 ZTools 中开启「超级面板」 +1. 按快捷键呼出 ZTools 主搜索框(默认快捷键为 `Alt + 空格`); +2. 点击搜索框右上角的齿轮图标或头像进入 **「设置」**; +3. 在左侧菜单中选择 **「超级面板」**; +4. 勾选 **「开启超级面板」**; +5. 在弹出方式中选择 **「长按鼠标中键」**(推荐长按时长设定为 **400ms ~ 500ms**)。 + +### 步骤 2:将「快速填充密码」固定到超级面板 +1. 在 ZTools 搜索栏输入指令:`填密码` 或 `pwd`; +2. 搜索结果列表中将出现带有蓝色锁图标的 **「快速填充密码」**; +3. **在该条目上单击鼠标右键**; +4. 在右键上下文菜单中点击 **「固定到超级面板」**; +5. 此时该条目右下角会出现一枚固定的图钉图标,表示已成功收录至超级面板。 + +--- + +## 🚀 第二部分:日常使用完整操作流 + +### 1. 就地长按唤起 +- 在任意浏览器或客户端登录界面时,请先确认光标位置: + - 若要使用 **「账号+密码」双填**:请用鼠标左键点入**账号/用户名输入框**; + - 若只想 **单填「密码」**:请用鼠标左键点入**密码输入框**; +- 此时直接在当前光标位置,**长按鼠标中键约 0.5 秒**,鼠标指针旁将弹出 ZTools 超级面板。 + +### 2. 选取密码指令 +- 在弹出的超级面板中,直接左键点击 **「快速选择并填充密码」** 图标(也可以直接按下图标对应的快捷数字键)。 + +### 3. 极速多词检索 +- 屏幕将弹出轻量悬浮选密窗口; +- 支持**空格分隔多关键词**检索(同时匹配平台名称、账号与备注)及关键词高亮,未匹配时支持一键创建条目; +- 支持键盘 `↑`、`↓` 快速移动高亮条目,前 9 条支持 `Alt+1~9` 直接选中填充; +- 按 `Ctrl+C` 可直接复制当前选中密码(支持智能定时清理)。 + +### 4. 一键安全回填 +- 顶部搜索栏右侧提供「回车: 双填 / 仅密码」切换胶囊,可随时切换默认 `Enter` 策略; +- 每个条目右侧提供三个独立按钮,按需点击: + - **「账号+密码」**:填入账号 ➔ 等待消费并 `Tab` 切到密码框 ➔ 填入密码(需光标在账号框); + - **「账号」**:仅把账号填入当前光标所在输入框; + - **「密码」**:仅把密码填入当前光标所在输入框(需光标在密码框); +- 键盘快捷键:`Enter` 按当前默认策略填充、`Shift+Enter` 仅密码、`Alt+Enter` 仅账号; +- 插件悬浮窗瞬间隐去后,底层引擎严格串行等待焦点恢复并逐框落盘校验填充,彻底防止账号密码填反; +- 系统剪贴板将在设定秒数(默认 10 秒)后智能擦除密码残留(若期间已复制其他非密码内容,绝不会误清)。 + +--- + +## 💡 第三部分:常见场景与避坑指南 + +### 1. 遇到禁止粘贴的网页/系统(如网银、政企平台、安全终端) +- 某些前端页面屏蔽了键盘 `Ctrl+V` 或鼠标粘贴事件; +- **解决方案**: + 1. 呼出本插件的完整管理面板(搜索 `密码管理` 或点击设置图标); + 2. 进入「首选项设置」; + 3. 将 **自动填充模式** 切换为 **「模拟键盘打字 (hideMainWindowTypeString)」**; + 4. 保存后,插件将使用底层 Unicode 虚拟键盘将密码逐字按键输入,彻底绕过网页端的一切粘贴拦截。 + +### 2. 目标应用程序以「管理员身份运行」 +- **表现**:在网页和普通记事本里可以自动填充,但发现在某些终端(如管理员 PowerShell、以管理员身份运行的编辑器)中无法粘贴; +- **原因**:Windows 系统的 UIPI(用户界面特权隔离)机制,严禁普通权限软件向管理员权限窗口发送模拟按键; +- **解决方案**:将 **ZTools 也右键设置为「以管理员身份运行」**,权限对齐后即可全域畅通无阻。 + +### 3. 特殊 Win32 MDI 架构编辑器(如 Notepad++) +- Notepad++ 的文本区域是一个独立的 `Scintilla` 子窗口。长按鼠标中键唤起超级面板时,Scintilla 默认会响应中键进入滚动状态并暂时隐藏 Caret 光标; +- 插件现已内置 **450ms 焦点自愈与二次防丢保障**,彻底解决窗口恢复时的光标失焦与物理按键未弹起冲突; +- 若您的电脑安装了大量 Notepad++ 插件导致窗口恢复更慢,可在插件「设置」中将「前台焦点恢复等待时长」调至 **600ms**。 + +### 4. 首次使用与锁屏保护 +- 每次系统重启或手动锁定时,插件处于零知识 AES-256-GCM 本地加密锁定状态; +- 此时长按中键触发会先展示 4 位 PIN 输入框,输完 PIN 后自动解锁并记忆内存,随后的多次填充均无须再次输密。 diff --git a/plugins/ztools-quick-pwd/README.md b/plugins/ztools-quick-pwd/README.md new file mode 100644 index 000000000..6df818fd1 --- /dev/null +++ b/plugins/ztools-quick-pwd/README.md @@ -0,0 +1,134 @@ +# 快速密码填充 (ZTools 插件) + +本地 AES-256-GCM 高度安全加密的密码存储与自动填充插件。支持长按鼠标中键或快捷指令一键将密码填入当前光标所在输入框,零额外依赖,纯本地运行。 + +![logo](logo.png) + +## ✨ 核心特性 + +- **高强度本地加密**:采用 PBKDF2 (SHA-256, 100,000次迭代) 派生主密钥,所有敏感数据均通过 **AES-256-GCM** 加密存储,密码永不离机。 +- **长按鼠标中键一键呼出**:在任意输入框内长按鼠标中键或唤出超级面板,即刻就地呼出快捷选密面板。 +- ⚡ **严格保序无感填充**:选中条目后按 `Enter`,支持**极速粘贴**或**模拟键盘逐字键入**(支持防粘贴输入框),双框联动严格串行校验绝不串位,并智能定时清空剪贴板(仅清理敏感密码,不误清后续复制文本)。 +- ⌨️ **全键盘流支持**:快捷模式支持空格多词即时检索与高亮,支持 `↑` `↓` 移动、`Enter` 回填、`Shift+Enter` 仅密码、`Alt+Enter` 仅账号、`Alt+1~9` 数字直选、`Ctrl+C` 复制密码、`Esc` 清空/关闭。 +- 🎯 **三键分离与常用排序**:支持条目置顶与使用频率智能排序;每条记录提供「账号+密码」「账号」「密码」三个独立按钮,顶部可一键切换默认回车策略。 +- 🔐 **完整安全与备份工具**:支持备注字段、16 位随机强密码生成器与强度评估、修改主密码、空闲自动锁定及加密备份导入导出。 +- **多平台完美兼容**:全面支持 Windows、macOS 和 Linux,原生调用各平台剪贴板与输入接口。 +- **自适应深浅主题**:现代毛玻璃界面风格,完美适配系统的浅色/深色模式。 +- **零构建 / 零第三方依赖**:仅使用 Node.js 核心内置模块与原生 Web 规范。 + +--- + +## 🚀 功能指令 + +在 ZTools 搜索框输入以下关键字即可快速唤起: + +| 快捷指令 | 功能说明 | +| :--- | :--- | +| `密码` / `pwd` / `填密` / `密码管理` / `password` | 打开密码管理器(完整增删改查与设置界面) | +| `填密码` / `快速填充` / `quick pwd` | 快速选择并填充密码(极简悬浮列表) | + +--- + +## 🛠️ 安装与使用 + +### 1. 安装方式 +1. 打开 ZTools 设置中的 **插件管理** -> **开发者开发中插件**。 +2. 点击 **添加开发插件**,选择当前插件根目录(包含 `plugin.json` 的目录)。 +3. 安装完成后即可使用。 + +### 2. 初始化 +首次启动时,插件会要求您设置一个 **主密码 PIN**(至少 4 位): +- 该主密码将作为派生主密钥(MasterKey)的唯一凭借。 +- 密码库完全本地加密存储在 ZTools 用户数据目录下的 `ztools-quick-pwd/vault.json` 中。 +- 请妥善保管主密码,一旦遗忘,因零知识加密架构无法找回。 + +--- + +## 📖 超级面板使用指南(长按中键呼出极速填充) + +这是日常使用本插件**最便捷、最高效**的使用姿势:在任何网页或客户端的密码框前,无需切出大窗口,就地长按鼠标中键即可呼出选单完成自动填入。 + +### ⚙️ 前置配置流程(仅需设置一次) + +#### 步骤 1:在 ZTools 中启用超级面板 +1. 按快捷键呼出 ZTools 主面板(默认 `Alt + 空格`); +2. 点击右上角头像或齿轮图标进入 **「设置」 ➔ 「超级面板」**; +3. 勾选 **「开启超级面板」**; +4. 触发方式勾选 **「长按鼠标中键」**(推荐触发延迟设为 **400ms ~ 500ms**)。 + +#### 步骤 2:将「快速填充密码」固定到超级面板 +1. 在 ZTools 搜索栏输入:`填密码` 或 `pwd`; +2. 在搜索结果列表中找到 **「快速填充密码」** 插件指令; +3. 在该条目上 **单击鼠标右键**; +4. 在弹出的右键菜单中点击 **「固定到超级面板」**(图标右下角将出现固定图钉标记)。 + +--- + +### 🚀 日常使用路径(工作流) + +``` +[1. 光标聚焦密码框] ➔ [2. 长按鼠标中键 0.5s 弹出超级面板] ➔ [3. 点击「填密码」图标] + ↓ +[6. 密码自动安全填入] ⬅ [5. Enter 或点击目标条目] ⬅ [4. 极简选单检索选择] +``` + +1. **就地唤起**: + 若使用 **「账号+密码」双填**,请将光标点入登录页的**账号输入框**;若只想**单填密码**,请将光标点入**密码输入框**。随后直接**按住鼠标中键约 0.5 秒**; +2. **呼出快捷菜单**: + 光标旁将就地弹出 ZTools 超级面板,点击固定的 **「快速选择并填充密码」** 图标(或直接按对应的序号数字键); +3. **即时筛选与直选**: + 屏幕就地弹出极简悬浮列表,支持空格分隔多关键词按名称/账号/备注即时搜索与高亮,支持键盘 `↑` `↓` 切换、`Alt+1~9` 直选或 `Ctrl+C` 复制密码; +4. **一键安全回填**: + 条目右侧提供三个按钮,按需点击即可: + - **「账号+密码」**:填入账号 ➔ 等待页面消费并自动 `Tab` 切换 ➔ 填入密码(光标需放在**账号框**,默认回车同效); + - **「账号」**:只把账号粘贴到当前光标所在输入框(`Alt+Enter` 同效); + - **「密码」**:只把密码粘贴到当前光标所在输入框(光标需放在**密码框**,`Shift+Enter` 同效); + - 选密窗口瞬间自动隐去,目标输入框在恢复焦点后严格保序自动填入; + - 10 秒后智能擦除系统剪贴板中的密码残留(若期间已复制其他内容则不会误清)。 + +--- + +### 💡 常见场景与避坑指南 + +1. **遇到禁止粘贴的输入框(如某些银行、政企内网网页、远程桌面)**: + - 打开密码管理器主界面 ➔ 点击右上角 **「设置」**; + - 将「自动填充模式」切换为 **「模拟键盘键入 (hideMainWindowTypeString)」**; + - 插件将通过底层 Unicode 按键逐字打入,轻松绕过网页前端的复制粘贴拦截。 +2. **目标应用以管理员身份运行(如某些环境下的 Notepad++ 或终端)**: + - Windows 的 UIPI(用户界面特权隔离)机制会拦截普通权限向管理员权限窗口发送的模拟输入; + - 如需在管理员权限应用中自动填入,建议将 **ZTools 也右键设置为「以管理员身份运行」**。 +3. **锁屏或重启后首次使用**: + - 首次触发时会弹出快速解锁界面,输入主密码 PIN 后立即进入选密流程。 +--- + +## 🛡️ 安全架构设计 + +1. **零知识存储**: + - 不存储用户的主密码明文,仅保存加盐派生后用于校验的 AES-GCM 令牌。 + - 每次加密均生成全新的 12 字节随机 IV,杜绝重放与模式推断攻击。 +2. **敏感内存隔离**: + - 主密钥仅在插件解锁期间驻留内存,插件锁定时或插件关闭时立即清空内存引用。 + - 监听 `ztools.onPluginOut`,插件退出时自动销毁后台监听与解密密钥。 +3. **剪贴板防残留**: + - 自动模拟粘贴后启动定时器,10 秒内自动清空系统剪贴板,避免密码泄露给其他应用程序。 +4. **数据原子性持久化**: + - 写入 `vault.json` 时采用临时文件 + `fs.renameSync` 原子写入,防止掉电或崩溃导致数据文件损坏。 + +--- + +## 跨平台适配说明 (Windows / macOS / Linux) + +| 平台 | 呼出方式 | 自动填充机制 | +| :--- | :--- | :--- | +| **Windows** | 长按鼠标中键 (超级面板 / 全局 Hook) 或 全局快捷键 | `hideMainWindowPasteText` (Ctrl+V) 或 `hideMainWindowTypeString` | +| **macOS** | 长按鼠标中键 (ZTools 原生超级面板) 或 全局快捷键 (如 `⌥+Q`) | `hideMainWindowPasteText` (⌘+V) 或 `hideMainWindowTypeString` | +| **Linux (X11)** | 长按鼠标中键 (ZTools 超级面板 / xinput) 或 全局快捷键 | `hideMainWindowPasteText` (Ctrl+V) 或 `hideMainWindowTypeString` | + +> **提示**:在 macOS 上因系统沙盒安全性要求,强烈推荐在 ZTools 搜索框搜 `填密码` ➔ 右键固定到「超级面板」,或在「全局快捷键」绑定热键,可获得最稳定流畅的无感填充体验。 + +--- + +## 作者与授权协议 + +- **作者**:wangtao +- **开源协议**:MIT License diff --git a/plugins/ztools-quick-pwd/index.css b/plugins/ztools-quick-pwd/index.css new file mode 100644 index 000000000..f9f3bf152 --- /dev/null +++ b/plugins/ztools-quick-pwd/index.css @@ -0,0 +1,1047 @@ +:root { + --bg-primary: #ffffff; + --bg-secondary: #f8fafc; + --bg-hover: #f1f5f9; + --bg-active: #e2e8f0; + --border-color: #e2e8f0; + --text-primary: #0f172a; + --text-secondary: #64748b; + --text-muted: #94a3b8; + --accent-color: #3b82f6; + --accent-hover: #2563eb; + --danger-color: #ef4444; + --danger-hover: #dc2626; + --success-color: #10b981; + --warning-color: #f59e0b; + --pin-color: #f59e0b; + --mark-bg: rgba(59, 130, 246, 0.16); + --mark-color: #1d4ed8; + --card-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.07), 0 2px 4px -2px rgba(0, 0, 0, 0.05); + --modal-bg: rgba(255, 255, 255, 0.98); + --overlay-bg: rgba(15, 23, 42, 0.45); +} + +html.dark { + --bg-primary: #1e293b; + --bg-secondary: #0f172a; + --bg-hover: #334155; + --bg-active: #475569; + --border-color: #334155; + --text-primary: #f8fafc; + --text-secondary: #94a3b8; + --text-muted: #64748b; + --accent-color: #3b82f6; + --accent-hover: #60a5fa; + --danger-color: #f87171; + --danger-hover: #ef4444; + --success-color: #34d399; + --warning-color: #fbbf24; + --pin-color: #fbbf24; + --mark-bg: rgba(96, 165, 250, 0.25); + --mark-color: #93c5fd; + --card-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.3), 0 2px 4px -2px rgba(0, 0, 0, 0.2); + --modal-bg: rgba(30, 41, 59, 0.98); + --overlay-bg: rgba(0, 0, 0, 0.7); +} + +* { + box-sizing: border-box; + margin: 0; + padding: 0; + user-select: none; + font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif; +} + +body { + background-color: var(--bg-primary); + color: var(--text-primary); + overflow: hidden; + font-size: 14px; + line-height: 1.5; +} + +input, button, select { + font-family: inherit; + font-size: inherit; +} + +/* 自定义细滚动条 */ +::-webkit-scrollbar { + width: 6px; + height: 6px; +} +::-webkit-scrollbar-track { + background: transparent; +} +::-webkit-scrollbar-thumb { + background: var(--border-color); + border-radius: 3px; +} +::-webkit-scrollbar-thumb:hover { + background: var(--text-muted); +} + +/* 隐藏视图通用 */ +.view { + display: none; + width: 100vw; + height: 100vh; + box-sizing: border-box; +} + +.view.active { + display: flex; + flex-direction: column; +} + +/* 按钮通用 */ +.btn { + display: inline-flex; + align-items: center; + justify-content: center; + padding: 6px 14px; + border-radius: 6px; + border: 1px solid var(--border-color); + background: var(--bg-secondary); + color: var(--text-primary); + cursor: pointer; + transition: all 0.15s ease; + font-weight: 500; + font-size: 13px; +} +.btn:hover { + background: var(--bg-hover); +} +.btn-primary { + background: var(--accent-color); + color: #ffffff; + border-color: var(--accent-color); +} +.btn-primary:hover { + background: var(--accent-hover); + border-color: var(--accent-hover); +} +.btn-danger { + background: var(--danger-color); + color: #ffffff; + border-color: var(--danger-color); +} +.btn-danger:hover { + background: var(--danger-hover); + border-color: var(--danger-hover); +} +.btn-text { + background: transparent; + border: none; + color: var(--text-secondary); + cursor: pointer; + display: inline-flex; + align-items: center; + justify-content: center; +} +.btn-text:hover { + color: var(--text-primary); +} + +/* ================= 视图 1:解锁 / 首次设置 ================= */ +#view-unlock { + align-items: center; + justify-content: center; + padding: 24px 20px; +} + +.unlock-box { + width: 100%; + max-width: 340px; + text-align: center; + display: flex; + flex-direction: column; + align-items: center; + gap: 14px; +} + +.unlock-logo { + width: 52px; + height: 52px; + object-fit: contain; +} + +.unlock-title { + font-size: 18px; + font-weight: 600; +} + +.unlock-desc { + font-size: 13px; + color: var(--text-secondary); + margin-top: -6px; +} + +.unlock-input-group { + width: 100%; +} + +.unlock-box input[type="password"], +.unlock-box input[type="text"] { + width: 100%; + padding: 10px 38px 10px 14px; + border-radius: 8px; + border: 1px solid var(--border-color); + background: var(--bg-secondary); + color: var(--text-primary); + outline: none; + font-size: 15px; + text-align: center; + letter-spacing: 2px; + user-select: text; +} +.unlock-box input:focus { + border-color: var(--accent-color); +} + +.unlock-box .btn-submit { + width: 100%; + padding: 10px 0; + font-size: 14px; +} + +.unlock-skip-btn { + font-size: 12px; + color: var(--text-muted); + padding: 4px 8px; + border-radius: 4px; + transition: color 0.15s, background 0.15s; +} + +.unlock-skip-btn:hover { + color: var(--accent-color); + background: rgba(59, 130, 246, 0.08); +} + +@keyframes shake { + 0%, 100% { transform: translateX(0); } + 20% { transform: translateX(-6px); } + 40% { transform: translateX(6px); } + 60% { transform: translateX(-4px); } + 80% { transform: translateX(4px); } +} + +.shake { + animation: shake 0.35s ease; + border-color: var(--danger-color) !important; +} + +/* ================= 视图 2:极简快捷选密 ================= */ +#view-quick { + background: var(--bg-primary); + height: 100vh; +} + +.quick-search-bar { + display: flex; + align-items: center; + gap: 8px; + padding: 9px 12px; + border-bottom: 1px solid var(--border-color); + background: var(--bg-secondary); + flex-shrink: 0; +} + +.quick-search-bar svg { + width: 17px; + height: 17px; + fill: var(--text-muted); + flex-shrink: 0; +} + +.quick-search-bar input { + flex: 1; + min-width: 80px; + border: none; + background: transparent; + color: var(--text-primary); + outline: none; + font-size: 14px; + user-select: text; +} + +.quick-mode-pill { + font-size: 11px; + line-height: 1; + padding: 5px 9px; + border-radius: 999px; + border: 1px solid rgba(59, 130, 246, 0.35); + background: rgba(59, 130, 246, 0.1); + color: var(--accent-color); + cursor: pointer; + white-space: nowrap; + flex-shrink: 0; + font-weight: 500; + transition: all 0.15s ease; +} + +.quick-mode-pill:hover { + background: rgba(59, 130, 246, 0.18); +} + +.quick-mode-pill.is-pwd-only { + border-color: var(--border-color); + background: var(--bg-primary); + color: var(--text-secondary); +} + +.quick-mgr-btn { + display: inline-flex; + align-items: center; + justify-content: center; + padding: 5px; + border-radius: 5px; + color: var(--text-muted); + cursor: pointer; + transition: all 0.15s ease; + flex-shrink: 0; +} +.quick-mgr-btn:hover { + color: var(--accent-color); + background: var(--bg-hover); +} + +.quick-list { + flex: 1; + min-height: 0; + overflow-y: auto; + padding: 4px 0; + list-style: none; +} + +.quick-item { + display: flex; + align-items: center; + justify-content: space-between; + gap: 8px; + padding: 7px 12px; + cursor: pointer; + border-left: 3px solid transparent; + transition: background 0.1s; +} + +.quick-item:hover, .quick-item.selected { + background-color: var(--bg-hover); +} + +.quick-item.selected { + border-left-color: var(--accent-color); +} + +.quick-item-main { + display: flex; + align-items: center; + gap: 8px; + min-width: 0; + flex: 1; + overflow: hidden; +} + +.quick-item-index { + width: 18px; + height: 18px; + border-radius: 4px; + background: var(--bg-secondary); + border: 1px solid var(--border-color); + color: var(--text-muted); + font-size: 11px; + display: inline-flex; + align-items: center; + justify-content: center; + flex-shrink: 0; +} + +.quick-item.selected .quick-item-index { + border-color: rgba(59, 130, 246, 0.4); + color: var(--accent-color); +} + +.quick-pin-icon { + display: inline-flex; + align-items: center; + color: var(--pin-color); + flex-shrink: 0; +} + +.quick-item-text { + display: flex; + align-items: center; + gap: 8px; + min-width: 0; + overflow: hidden; + flex: 1; +} + +.quick-item-label { + font-weight: 500; + color: var(--text-primary); + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; +} + +.quick-item-user { + font-size: 12px; + color: var(--text-secondary); + background: var(--bg-secondary); + padding: 1px 6px; + border-radius: 4px; + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; + max-width: 170px; + flex-shrink: 1; +} + +.quick-item-note { + font-size: 11px; + color: var(--text-muted); + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; + max-width: 120px; +} + +.quick-match-mark { + background: var(--mark-bg); + color: var(--mark-color); + border-radius: 2px; + padding: 0 1px; + font-weight: 600; +} + +.quick-item-action { + font-size: 12px; + display: flex; + align-items: center; + gap: 5px; + flex: 0 0 auto; +} + +.quick-action-btn { + font-size: 11px; + line-height: 1; + padding: 5px 8px; + border-radius: 4px; + border: 1px solid var(--border-color); + background: var(--bg-secondary); + color: var(--text-secondary); + cursor: pointer; + white-space: nowrap; + flex: 0 0 auto; + transition: all 0.12s ease; +} + +.quick-action-btn:hover:not(:disabled) { + border-color: var(--accent-color); + color: var(--accent-color); + background: rgba(59, 130, 246, 0.08); +} + +.quick-action-btn.is-default { + border-color: rgba(59, 130, 246, 0.45); + color: var(--accent-color); + background: rgba(59, 130, 246, 0.12); + font-weight: 600; +} + +.quick-action-btn.disabled, +.quick-action-btn:disabled { + opacity: 0.4; + cursor: not-allowed; +} + +.quick-empty-wrap { + padding: 28px 16px; + text-align: center; + color: var(--text-muted); + display: flex; + flex-direction: column; + align-items: center; + gap: 10px; + font-size: 13px; +} + +.quick-footer { + height: 28px; + padding: 0 12px; + border-top: 1px solid var(--border-color); + background: var(--bg-secondary); + display: flex; + align-items: center; + gap: 12px; + font-size: 11px; + color: var(--text-muted); + flex-shrink: 0; + overflow: hidden; + white-space: nowrap; +} + +.quick-footer kbd { + display: inline-block; + padding: 1px 4px; + border-radius: 3px; + border: 1px solid var(--border-color); + background: var(--bg-primary); + color: var(--text-secondary); + font-size: 10px; + font-family: inherit; + margin-right: 2px; +} + +@media (max-width: 560px) { + .quick-footer .hide-narrow, + .quick-item-note { + display: none; + } +} + +/* ================= 视图 3:完整密码管理 ================= */ +#view-manager { + height: 100vh; +} + +.mgr-header { + display: flex; + align-items: center; + justify-content: space-between; + padding: 12px 18px; + border-bottom: 1px solid var(--border-color); + background: var(--bg-secondary); + flex-shrink: 0; +} + +.mgr-title-area { + display: flex; + align-items: center; + gap: 10px; +} + +.mgr-logo { + width: 28px; + height: 28px; +} + +.mgr-title { + font-size: 16px; + font-weight: 600; +} + +.mgr-count { + font-size: 11px; + padding: 2px 8px; + border-radius: 999px; + background: var(--bg-hover); + color: var(--text-secondary); + font-weight: 500; +} + +.mgr-actions { + display: flex; + align-items: center; + gap: 8px; +} + +.mgr-actions .btn-text { + padding: 6px; + border-radius: 6px; +} +.mgr-actions .btn-text:hover { + background: var(--bg-hover); +} + +.mgr-toolbar { + display: flex; + align-items: center; + justify-content: space-between; + padding: 10px 18px; + gap: 12px; + flex-shrink: 0; +} + +.mgr-search { + flex: 1; + max-width: 360px; + display: flex; + align-items: center; + gap: 6px; + padding: 6px 10px; + border-radius: 6px; + border: 1px solid var(--border-color); + background: var(--bg-secondary); +} + +.mgr-search:focus-within { + border-color: var(--accent-color); +} + +.mgr-search input { + border: none; + outline: none; + background: transparent; + width: 100%; + color: var(--text-primary); + user-select: text; + font-size: 13px; +} + +.mgr-content { + flex: 1; + min-height: 0; + overflow-y: auto; + padding: 0 18px 18px; +} + +.mgr-table { + width: 100%; + border-collapse: collapse; + text-align: left; +} + +.mgr-table thead th { + position: sticky; + top: 0; + background: var(--bg-primary); + z-index: 2; + padding: 10px 10px; + font-weight: 500; + color: var(--text-secondary); + border-bottom: 1px solid var(--border-color); + font-size: 12px; +} + +.mgr-table td { + padding: 9px 10px; + border-bottom: 1px solid var(--border-color); + font-size: 13px; + user-select: text; + vertical-align: middle; +} + +.mgr-table tbody tr:hover td { + background: var(--bg-hover); +} + +.mgr-label-cell { + display: flex; + align-items: center; + gap: 6px; + font-weight: 500; +} + +.mgr-label-note { + font-size: 11px; + color: var(--text-muted); + margin-top: 2px; + max-width: 220px; + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; +} + +.mgr-user-copy { + display: inline-flex; + align-items: center; + gap: 4px; + max-width: 200px; + padding: 2px 6px; + margin-left: -6px; + border-radius: 4px; + cursor: pointer; + color: var(--text-primary); + transition: background 0.15s, color 0.15s; +} + +.mgr-user-copy:hover { + background: rgba(59, 130, 246, 0.1); + color: var(--accent-color); +} + +.mgr-user-copy-text { + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; +} + +.mgr-item-actions { + display: flex; + align-items: center; + justify-content: flex-end; + gap: 4px; +} + +.icon-btn { + width: 28px; + height: 28px; + border-radius: 6px; + border: none; + background: transparent; + color: var(--text-secondary); + display: inline-flex; + align-items: center; + justify-content: center; + cursor: pointer; + transition: all 0.15s ease; +} + +.icon-btn:hover { + background: var(--bg-active); + color: var(--text-primary); +} + +.icon-btn.pinned { + color: var(--pin-color); +} + +.icon-btn.danger:hover { + background: rgba(239, 68, 68, 0.12); + color: var(--danger-color); +} + +/* ================= 弹窗与抽屉 ================= */ +.modal-overlay { + display: none; + position: fixed; + inset: 0; + background: var(--overlay-bg); + backdrop-filter: blur(2px); + z-index: 100; + align-items: center; + justify-content: center; + padding: 14px; + box-sizing: border-box; +} + +.modal-overlay.active { + display: flex; +} + +.modal-box { + width: 95%; + max-width: 520px; + max-height: calc(100vh - 28px); + background: var(--modal-bg); + border: 1px solid var(--border-color); + border-radius: 10px; + box-shadow: var(--card-shadow); + overflow: hidden; + display: flex; + flex-direction: column; + box-sizing: border-box; +} + +.confirm-box { + max-width: 400px; +} + +.confirm-message { + font-size: 13px; + color: var(--text-secondary); + line-height: 1.6; + white-space: pre-line; +} + +.modal-header { + display: flex; + align-items: center; + justify-content: space-between; + padding: 12px 18px; + border-bottom: 1px solid var(--border-color); + font-weight: 600; + flex-shrink: 0; +} + +.modal-body { + padding: 14px 18px; + display: flex; + flex-direction: column; + gap: 12px; + overflow-y: auto; + flex: 1; + min-height: 0; +} + +.form-group { + display: flex; + flex-direction: column; + gap: 5px; +} + +.form-group label { + font-size: 12px; + color: var(--text-secondary); + font-weight: 500; +} + +.form-group input { + padding: 8px 12px; + border-radius: 6px; + border: 1px solid var(--border-color); + background: var(--bg-secondary); + color: var(--text-primary); + outline: none; + user-select: text; + font-size: 13px; +} + +.form-group input:focus { + border-color: var(--accent-color); +} + +.pwd-input-group { + position: relative; + display: flex; + align-items: center; +} + +.pwd-input-group input { + flex: 1; + padding-right: 42px; +} + +.pwd-input-with-tools input { + padding-right: 72px; +} + +.pwd-toggle-btn, +.pwd-tool-btn { + position: absolute; + background: none; + border: none; + cursor: pointer; + color: var(--text-muted); + padding: 4px; + border-radius: 4px; + display: inline-flex; + align-items: center; + justify-content: center; + transition: color 0.15s, background 0.15s; +} + +.pwd-toggle-btn { + right: 8px; +} + +.pwd-tool-btn { + right: 36px; +} + +.pwd-toggle-btn:hover, +.pwd-tool-btn:hover { + color: var(--accent-color); + background: var(--bg-hover); +} + +.view-copy-btn { + position: absolute; + right: 6px; + font-size: 12px; + padding: 3px 8px; + border-radius: 4px; + color: var(--accent-color); +} +.view-copy-btn:hover { + background: rgba(59, 130, 246, 0.1); +} + +/* 密码强度条 */ +.pwd-strength-wrap { + display: flex; + align-items: center; + gap: 8px; + margin-top: 2px; +} + +.pwd-strength-track { + flex: 1; + height: 4px; + border-radius: 2px; + background: var(--border-color); + overflow: hidden; +} + +.pwd-strength-fill { + height: 100%; + width: 0%; + border-radius: 2px; + transition: width 0.2s ease, background-color 0.2s ease; +} + +.pwd-strength-text { + font-size: 11px; + min-width: 28px; + text-align: right; + font-weight: 500; +} + +.modal-footer { + display: flex; + justify-content: flex-end; + gap: 10px; + padding: 10px 18px; + border-top: 1px solid var(--border-color); + background: var(--bg-secondary); + flex-shrink: 0; +} + +/* 抽屉/设置 */ +.settings-section-title { + font-size: 11px; + font-weight: 600; + color: var(--accent-color); + text-transform: uppercase; + letter-spacing: 0.5px; + margin-top: 4px; +} + +.settings-item { + display: flex; + align-items: center; + justify-content: space-between; + padding: 8px 0; + gap: 14px; + border-bottom: 1px solid var(--border-color); +} + +.settings-label-group { + flex: 1; + min-width: 140px; + display: flex; + flex-direction: column; + gap: 2px; +} + +.settings-title { + font-weight: 500; + font-size: 13px; + color: var(--text-primary); +} + +.settings-subtitle { + font-size: 12px; + color: var(--text-muted); + line-height: 1.4; +} + +.settings-select { + max-width: 230px; + padding: 5px 8px; + border: 1px solid var(--border-color); + border-radius: 5px; + background: var(--bg-secondary); + color: var(--text-primary); + font-size: 12px; + outline: none; +} + +.settings-number { + width: 80px; + text-align: center; + padding: 4px 6px; + border: 1px solid var(--border-color); + border-radius: 5px; + background: var(--bg-secondary); + color: var(--text-primary); + font-size: 12px; + outline: none; +} + +.settings-action-row { + display: flex; + flex-wrap: wrap; + gap: 8px; + padding-top: 2px; +} + +.settings-item.is-disabled { + opacity: 0.5; +} + +.settings-item.is-disabled select { + cursor: not-allowed; +} + +.btn:disabled { + opacity: 0.45; + cursor: not-allowed; +} + +/* Switch 开关 */ +.switch { + position: relative; + display: inline-block; + width: 44px; + height: 24px; + flex-shrink: 0; +} + +.switch input { + opacity: 0; + width: 0; + height: 0; +} + +.slider { + position: absolute; + cursor: pointer; + top: 0; left: 0; right: 0; bottom: 0; + background-color: var(--border-color); + transition: .2s; + border-radius: 24px; +} + +.slider:before { + position: absolute; + content: ""; + height: 18px; + width: 18px; + left: 3px; + bottom: 3px; + background-color: white; + transition: .2s; + border-radius: 50%; +} + +input:checked + .slider { + background-color: var(--accent-color); +} + +input:checked + .slider:before { + transform: translateX(20px); +} + +/* Toast 提示 */ +#toast { + position: fixed; + bottom: 24px; + left: 50%; + transform: translateX(-50%) translateY(20px); + background: rgba(15, 23, 42, 0.92); + color: #fff; + padding: 8px 18px; + border-radius: 20px; + font-size: 13px; + pointer-events: none; + opacity: 0; + transition: all 0.22s ease; + z-index: 9999; + max-width: 85vw; + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; +} + +html.dark #toast { + background: rgba(248, 250, 252, 0.95); + color: #0f172a; +} + +#toast.show { + opacity: 1; + transform: translateX(-50%) translateY(0); +} diff --git a/plugins/ztools-quick-pwd/index.html b/plugins/ztools-quick-pwd/index.html new file mode 100644 index 000000000..85687f4c3 --- /dev/null +++ b/plugins/ztools-quick-pwd/index.html @@ -0,0 +1,389 @@ + + + + + + 快速密码填充 + + + + +
+
+ +
快速密码填充
+
请输入您的安全主密码 PIN
+ +
+ + +
+ + + + + +
+
+ + +
+ + + +
+ + +
+
+
+ + 密码管理器 + 0 条 +
+
+ + + + +
+
+ +
+ + +
+ +
+ + + + + + + + + + + + +
平台/网站名称用户名/账号 (点击复制)更新时间操作
+
+
+ + +
+ +
+ + + + + + + + + + + + + + + + + +
+ + + + diff --git a/plugins/ztools-quick-pwd/index.js b/plugins/ztools-quick-pwd/index.js new file mode 100644 index 000000000..8cec0a6c6 --- /dev/null +++ b/plugins/ztools-quick-pwd/index.js @@ -0,0 +1,1615 @@ +// DOM 元素引用 +const viewUnlock = document.getElementById('view-unlock'); +const viewQuick = document.getElementById('view-quick'); +const viewManager = document.getElementById('view-manager'); + +// 解锁视图 +const unlockTitle = document.getElementById('unlock-title'); +const unlockDesc = document.getElementById('unlock-desc'); +const unlockPin = document.getElementById('unlock-pin'); +const unlockPinConfirm = document.getElementById('unlock-pin-confirm'); +const unlockPinConfirmWrap = document.getElementById('unlock-pin-confirm-wrap'); +const btnToggleUnlockPin = document.getElementById('btn-toggle-unlock-pin'); +const btnToggleUnlockConfirm = document.getElementById('btn-toggle-unlock-confirm'); +const btnUnlockSubmit = document.getElementById('btn-unlock-submit'); +const btnSkipMasterPin = document.getElementById('btn-skip-master-pin'); + +// 快捷选密视图 +const quickFilterInput = document.getElementById('quick-filter-input'); +const quickList = document.getElementById('quick-list'); +const btnQuickModeToggle = document.getElementById('btn-quick-mode-toggle'); +const btnQuickOpenMgr = document.getElementById('btn-quick-open-mgr'); +const quickFooterPrimary = document.getElementById('quick-footer-primary'); + +// 管理视图 +const mgrSearchInput = document.getElementById('mgr-search-input'); +const mgrTableBody = document.getElementById('mgr-table-body'); +const mgrCount = document.getElementById('mgr-count'); +const btnAddEntry = document.getElementById('btn-add-entry'); +const btnOpenSettings = document.getElementById('btn-open-settings'); +const btnLockVault = document.getElementById('btn-lock-vault'); + +// 新增/编辑弹窗 +const modalEntry = document.getElementById('modal-entry'); +const modalEntryTitle = document.getElementById('modal-entry-title'); +const entryId = document.getElementById('entry-id'); +const entryLabel = document.getElementById('entry-label'); +const entryUsername = document.getElementById('entry-username'); +const entryPassword = document.getElementById('entry-password'); +const entryNote = document.getElementById('entry-note'); +const entryPwdRequired = document.getElementById('entry-pwd-required'); +const btnGenEntryPwd = document.getElementById('btn-gen-entry-pwd'); +const btnToggleEntryPwd = document.getElementById('btn-toggle-entry-pwd'); +const entryPwdStrength = document.getElementById('entry-pwd-strength'); +const entryPwdStrengthFill = document.getElementById('entry-pwd-strength-fill'); +const entryPwdStrengthText = document.getElementById('entry-pwd-strength-text'); +const btnSaveEntry = document.getElementById('btn-save-entry'); +const btnCancelEntry = document.getElementById('btn-cancel-entry'); +const btnCloseEntryModal = document.getElementById('btn-close-entry-modal'); + +// 查看详情弹窗 +const modalViewPwd = document.getElementById('modal-view-pwd'); +const viewLabel = document.getElementById('view-label'); +const viewUsername = document.getElementById('view-username'); +const viewPlainPwd = document.getElementById('view-plain-pwd'); +const viewNoteGroup = document.getElementById('view-note-group'); +const viewNote = document.getElementById('view-note'); +const btnCopyViewUser = document.getElementById('btn-copy-view-user'); +const btnCopyViewPwd = document.getElementById('btn-copy-view-pwd'); +const btnCloseViewModal = document.getElementById('btn-close-view-modal'); +const btnCloseViewBtn = document.getElementById('btn-close-view-btn'); + +// 设置弹窗 +const modalSettings = document.getElementById('modal-settings'); +const settingRequirePin = document.getElementById('setting-require-pin'); +const settingsItemAutoLock = document.getElementById('settings-item-auto-lock'); +const settingClearClipboard = document.getElementById('setting-clear-clipboard'); +const settingFillMode = document.getElementById('setting-fill-mode'); +const settingFillDelay = document.getElementById('setting-fill-delay'); +const settingTabDelay = document.getElementById('setting-tab-delay'); +const settingFillStrategy = document.getElementById('setting-fill-strategy'); +const settingAutoLock = document.getElementById('setting-auto-lock'); +const settingOpenStandalone = document.getElementById('setting-open-standalone'); +const btnOpenChangePin = document.getElementById('btn-open-change-pin'); +const btnExportVault = document.getElementById('btn-export-vault'); +const btnImportVault = document.getElementById('btn-import-vault'); +const inputImportVault = document.getElementById('input-import-vault'); +const btnDetachWindow = document.getElementById('btn-detach-window'); +const btnSaveSettings = document.getElementById('btn-save-settings'); +const btnCloseSettingsModal = document.getElementById('btn-close-settings-modal'); + +// 修改/开启主密码弹窗 +const modalChangePin = document.getElementById('modal-change-pin'); +const changePinTitle = document.getElementById('change-pin-title'); +const changeOldPinGroup = document.getElementById('change-old-pin-group'); +const changeOldPin = document.getElementById('change-old-pin'); +const changeNewPin = document.getElementById('change-new-pin'); +const changeConfirmPin = document.getElementById('change-confirm-pin'); +const btnSubmitChangePin = document.getElementById('btn-submit-change-pin'); +const btnCancelChangePin = document.getElementById('btn-cancel-change-pin'); +const btnCloseChangePinModal = document.getElementById('btn-close-change-pin-modal'); + +// 自定义确认弹窗 +const modalConfirm = document.getElementById('modal-confirm'); +const confirmTitle = document.getElementById('confirm-title'); +const confirmMessage = document.getElementById('confirm-message'); +const btnConfirmOk = document.getElementById('btn-confirm-ok'); +const btnConfirmCancel = document.getElementById('btn-confirm-cancel'); +const btnCloseConfirmModal = document.getElementById('btn-close-confirm-modal'); + +// 使用指南弹窗 +const btnOpenGuide = document.getElementById('btn-open-guide'); +const modalGuide = document.getElementById('modal-guide'); +const btnCloseGuideModal = document.getElementById('btn-close-guide-modal'); +const btnCloseGuideBtn = document.getElementById('btn-close-guide-btn'); + +const toastEl = document.getElementById('toast'); + +// 精致 SVG 图标常量 +const ICONS = { + eyeOpen: '', + eyeOff: '', + starFilled: '', + starOutline: '', + copy: '', + edit: '', + trash: '', + dice: '' +}; + +// 初始化固定按钮 SVG 图标 +if (btnToggleUnlockPin) btnToggleUnlockPin.innerHTML = ICONS.eyeOpen; +if (btnToggleUnlockConfirm) btnToggleUnlockConfirm.innerHTML = ICONS.eyeOpen; +if (btnGenEntryPwd) btnGenEntryPwd.innerHTML = ICONS.dice; +if (btnToggleEntryPwd) btnToggleEntryPwd.innerHTML = ICONS.eyeOpen; + +// 触发关键词(不用于快捷选密搜索词回填) +const QUICK_TRIGGER_CMDS = new Set(['填密码', '快速填充', 'quick pwd', 'pwd-quick-fill']); + +// 内部状态 +let currentTargetCode = 'pwd-manager'; +let quickAllEntries = []; +let filteredQuickItems = []; +let quickSelectedIndex = 0; +let isFillingInProgress = false; +let toastTimer = null; +let confirmResolver = null; +let lastActivityTouchAt = 0; +let pinModalMode = 'change'; // 'change' | 'enable' + +// ======================= 工具函数 ======================= +const STANDALONE_ALIVE_KEY = 'quick_pwd_standalone_alive_ts'; +const bus = typeof BroadcastChannel !== 'undefined' ? new BroadcastChannel('ztools_quick_pwd_bus') : null; + +function getWindowMode() { + const ztoolsObj = window.ztools || window.utools; + if (ztoolsObj && typeof ztoolsObj.getWindowType === 'function') { + return ztoolsObj.getWindowType(); // 'main' | 'browser' | 'detach' + } + return 'main'; +} + +function isDetached() { + const mode = getWindowMode(); + return mode === 'detach' || mode === 'browser'; +} + +function updateStandaloneHeartbeat() { + try { + localStorage.setItem(STANDALONE_ALIVE_KEY, String(Date.now())); + } catch (e) {} +} + +function clearStandaloneHeartbeat() { + try { + localStorage.removeItem(STANDALONE_ALIVE_KEY); + } catch (e) {} +} + +function startStandaloneHeartbeat() { + updateStandaloneHeartbeat(); + if (!window._standaloneHeartbeatTimer) { + window._standaloneHeartbeatTimer = setInterval(updateStandaloneHeartbeat, 1200); + window.addEventListener('beforeunload', clearStandaloneHeartbeat); + } +} + +// 节流上报用户活跃状态,驱动空闲自动锁定计时 +function notifyActivity() { + const now = Date.now(); + if (now - lastActivityTouchAt > 5000) { + lastActivityTouchAt = now; + if (window.pwdApi && typeof window.pwdApi.touchActivity === 'function') { + window.pwdApi.touchActivity(); + } + } +} + +['mousedown', 'keydown', 'input'].forEach((evtName) => { + window.addEventListener(evtName, notifyActivity, { passive: true }); +}); + +// 独立窗口环境初始化心跳与广播监听 +if (isDetached()) { + startStandaloneHeartbeat(); + window.addEventListener('focus', () => { + if (window.pwdApi && typeof window.pwdApi.bringToFront === 'function') { + window.pwdApi.bringToFront(); + } + }); +} + +if (bus) { + bus.onmessage = (event) => { + const msg = event.data; + if (!msg) return; + + if (msg.type === 'WAKE_UP') { + if (window.pwdApi && typeof window.pwdApi.bringToFront === 'function') { + window.pwdApi.bringToFront(); + } else { + window.focus(); + } + + if (msg.action) { + const act = msg.action; + currentTargetCode = act.code || 'pwd-manager'; + if (act.payload && typeof act.payload === 'string') { + const q = act.payload.trim(); + if (q && mgrSearchInput) { + mgrSearchInput.value = q; + } + } + if (window.pwdApi && !window.pwdApi.isUnlocked()) { + switchView('unlock'); + } else { + switchView('manager'); + } + } + } + }; +} + +function safeSetExpendHeight(height) { + const ztoolsObj = window.ztools || window.utools; + if (!ztoolsObj || typeof ztoolsObj.setExpendHeight !== 'function') return; + if (isDetached()) return; + ztoolsObj.setExpendHeight(height); +} + +// 防抖 Toast:连续调用时先清理上一个计时器,避免提前隐藏 +function showToast(msg, duration = 2000) { + if (toastTimer) { + clearTimeout(toastTimer); + toastTimer = null; + } + toastEl.textContent = msg; + toastEl.classList.add('show'); + toastTimer = setTimeout(() => { + toastEl.classList.remove('show'); + toastTimer = null; + }, duration); +} + +function escapeHtml(str) { + if (!str) return ''; + return String(str) + .replace(/&/g, '&') + .replace(//g, '>') + .replace(/"/g, '"') + .replace(/'/g, '''); +} + +function escapeRegExp(str) { + return String(str).replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); +} + +// 多关键词分词与匹配 +function parseSearchTokens(query) { + return (query || '').trim().toLowerCase().split(/\s+/).filter(Boolean); +} + +function matchEntry(item, tokens) { + if (!tokens || tokens.length === 0) return true; + const label = (item.label || '').toLowerCase(); + const username = (item.username || '').toLowerCase(); + const note = (item.note || '').toLowerCase(); + return tokens.every((t) => label.includes(t) || username.includes(t) || note.includes(t)); +} + +// 先转义 HTML 再包裹高亮标签,确保安全与准确 +function highlightText(str, tokens) { + const safe = escapeHtml(str); + if (!safe || !tokens || tokens.length === 0) return safe; + const escapedTokens = tokens.map((t) => escapeRegExp(escapeHtml(t))).filter(Boolean); + if (escapedTokens.length === 0) return safe; + // 按长度降序匹配,避免短词截断长词 + escapedTokens.sort((a, b) => b.length - a.length); + const regex = new RegExp(`(${escapedTokens.join('|')})`, 'gi'); + return safe.replace(regex, '$1'); +} + +function formatDate(timestamp) { + if (!timestamp) return '-'; + const d = new Date(timestamp); + const pad = (n) => String(n).padStart(2, '0'); + return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}`; +} + +// 统一密码输入框显隐切换绑定 +function bindPasswordToggle(inputEl, btnEl) { + if (!inputEl || !btnEl) return; + btnEl.addEventListener('click', () => { + if (inputEl.type === 'password') { + inputEl.type = 'text'; + btnEl.innerHTML = ICONS.eyeOff; + } else { + inputEl.type = 'password'; + btnEl.innerHTML = ICONS.eyeOpen; + } + inputEl.focus(); + }); +} + +bindPasswordToggle(unlockPin, btnToggleUnlockPin); +bindPasswordToggle(unlockPinConfirm, btnToggleUnlockConfirm); +bindPasswordToggle(entryPassword, btnToggleEntryPwd); + +// 通用异步复制封装(密码走自动清理,非密码走普通复制) +async function copyTextSafe(text, isSecret) { + if (!text) return false; + if (window.pwdApi) { + if (isSecret && typeof window.pwdApi.copySecret === 'function') { + return window.pwdApi.copySecret(text); + } + if (!isSecret && typeof window.pwdApi.copyPlainText === 'function') { + return window.pwdApi.copyPlainText(text); + } + } + const ztoolsObj = window.ztools || window.utools; + if (ztoolsObj && typeof ztoolsObj.copyText === 'function') { + ztoolsObj.copyText(text); + return true; + } + if (navigator.clipboard && navigator.clipboard.writeText) { + await navigator.clipboard.writeText(text); + return true; + } + return false; +} + +// 自定义内联确认弹窗(替代 window.confirm,不触发失焦隐藏且适配深浅色) +function showConfirmDialog({ title = '确认操作', message = '', confirmText = '确认', danger = false } = {}) { + return new Promise((resolve) => { + if (confirmResolver) { + confirmResolver(false); + confirmResolver = null; + } + confirmTitle.textContent = title; + confirmMessage.textContent = message; + btnConfirmOk.textContent = confirmText; + btnConfirmOk.className = danger ? 'btn btn-danger' : 'btn btn-primary'; + modalConfirm.classList.add('active'); + confirmResolver = resolve; + setTimeout(() => btnConfirmOk.focus(), 30); + }); +} + +function closeConfirmDialog(result) { + modalConfirm.classList.remove('active'); + if (confirmResolver) { + const fn = confirmResolver; + confirmResolver = null; + fn(!!result); + } +} + +btnConfirmOk.addEventListener('click', () => closeConfirmDialog(true)); +btnConfirmCancel.addEventListener('click', () => closeConfirmDialog(false)); +btnCloseConfirmModal.addEventListener('click', () => closeConfirmDialog(false)); + +// 密码生成与强度评估 +function generateStrongPassword(length = 16) { + const upper = 'ABCDEFGHJKLMNPQRSTUVWXYZ'; + const lower = 'abcdefghijkmnopqrstuvwxyz'; + const digits = '23456789'; + const symbols = '!@#$%^&*_-+=?'; + const all = upper + lower + digits + symbols; + + const getRandInt = (max) => { + const arr = new Uint32Array(1); + crypto.getRandomValues(arr); + return arr[0] % max; + }; + + const chars = [ + upper[getRandInt(upper.length)], + lower[getRandInt(lower.length)], + digits[getRandInt(digits.length)], + symbols[getRandInt(symbols.length)] + ]; + + for (let i = chars.length; i < length; i++) { + chars.push(all[getRandInt(all.length)]); + } + + // Fisher-Yates 洗牌打乱顺序 + for (let i = chars.length - 1; i > 0; i--) { + const j = getRandInt(i + 1); + [chars[i], chars[j]] = [chars[j], chars[i]]; + } + return chars.join(''); +} + +function evaluatePasswordStrength(pwd) { + if (!pwd) return null; + let score = 0; + if (pwd.length >= 8) score += 1; + if (pwd.length >= 12) score += 1; + if (pwd.length >= 16) score += 1; + if (/[a-z]/.test(pwd)) score += 1; + if (/[A-Z]/.test(pwd)) score += 1; + if (/[0-9]/.test(pwd)) score += 1; + if (/[^a-zA-Z0-9]/.test(pwd)) score += 1; + + if (pwd.length < 6 || score <= 2) { + return { label: '弱', percent: 33, color: 'var(--danger-color)' }; + } + if (score <= 5) { + return { label: '中', percent: 66, color: 'var(--warning-color)' }; + } + return { label: '强', percent: 100, color: 'var(--success-color)' }; +} + +function updateEntryPasswordStrength() { + const val = entryPassword.value; + const info = evaluatePasswordStrength(val); + if (!info) { + entryPwdStrength.style.display = 'none'; + return; + } + entryPwdStrength.style.display = 'flex'; + entryPwdStrengthFill.style.width = `${info.percent}%`; + entryPwdStrengthFill.style.backgroundColor = info.color; + entryPwdStrengthText.textContent = info.label; + entryPwdStrengthText.style.color = info.color; +} + +// 切换视图(修复:先重置 quickFilterInput 与选中索引再渲染,避免旧过滤词残留) +function switchView(viewName, initialQuery = '') { + [viewUnlock, viewQuick, viewManager].forEach((v) => v.classList.remove('active')); + + if (viewName === 'unlock') { + viewUnlock.classList.add('active'); + safeSetExpendHeight(280); + setupUnlockView(); + } else if (viewName === 'quick') { + viewQuick.classList.add('active'); + quickFilterInput.value = initialQuery; + quickSelectedIndex = 0; + updateQuickModeDisplay(); + renderQuickList(true); + setTimeout(() => quickFilterInput.focus(), 20); + } else if (viewName === 'manager') { + viewManager.classList.add('active'); + safeSetExpendHeight(560); + if (btnDetachWindow) { + btnDetachWindow.style.display = isDetached() ? 'none' : 'inline-flex'; + } + syncMasterPinUiState(); + renderManagerList(); + setTimeout(() => mgrSearchInput.focus(), 20); + } +} + +// 同步主密码保护开关在管理页与设置弹窗中的 UI 状态 +function syncMasterPinUiState() { + if (!window.pwdApi || typeof window.pwdApi.isMasterPinRequired !== 'function') return; + const required = window.pwdApi.isMasterPinRequired(); + if (btnLockVault) { + btnLockVault.style.display = required ? 'inline-flex' : 'none'; + } + if (settingRequirePin) { + settingRequirePin.checked = required; + } + if (settingAutoLock) { + settingAutoLock.disabled = !required; + } + if (settingsItemAutoLock) { + settingsItemAutoLock.classList.toggle('is-disabled', !required); + } + if (btnOpenChangePin) { + btnOpenChangePin.disabled = !required; + btnOpenChangePin.title = required ? '修改当前主密码 PIN' : '当前处于免密模式,请先开启主密码保护'; + } +} + +// ======================= 解锁 / 初始设置 ======================= +function setupUnlockView() { + unlockPin.value = ''; + unlockPin.type = 'password'; + if (btnToggleUnlockPin) btnToggleUnlockPin.innerHTML = ICONS.eyeOpen; + + unlockPinConfirm.value = ''; + unlockPinConfirm.type = 'password'; + if (btnToggleUnlockConfirm) btnToggleUnlockConfirm.innerHTML = ICONS.eyeOpen; + + const isFirst = window.pwdApi.isFirstRun(); + if (isFirst) { + unlockTitle.textContent = '初始化主密码'; + unlockDesc.textContent = '请设置一个主密码 PIN (至少4位),用于加密本地密码库'; + if (unlockPinConfirmWrap) unlockPinConfirmWrap.style.display = 'flex'; + btnUnlockSubmit.textContent = '创建并解锁'; + if (btnSkipMasterPin) btnSkipMasterPin.style.display = 'inline-flex'; + safeSetExpendHeight(370); + } else { + unlockTitle.textContent = '快速密码填充'; + unlockDesc.textContent = '请输入您的安全主密码 PIN 解锁'; + if (unlockPinConfirmWrap) unlockPinConfirmWrap.style.display = 'none'; + btnUnlockSubmit.textContent = '解锁保险库'; + if (btnSkipMasterPin) btnSkipMasterPin.style.display = 'none'; + safeSetExpendHeight(260); + } + setTimeout(() => unlockPin.focus(), 50); +} + +function triggerInputShake(el) { + if (!el) return; + el.classList.remove('shake'); + void el.offsetWidth; + el.classList.add('shake'); + setTimeout(() => el.classList.remove('shake'), 400); +} + +function handleUnlockOrSetup() { + const pin = unlockPin.value; + const isFirst = window.pwdApi.isFirstRun(); + + if (!pin || pin.length < 4) { + showToast('主密码长度不能少于 4 位'); + triggerInputShake(unlockPin); + unlockPin.focus(); + return; + } + + if (isFirst) { + const confirmVal = unlockPinConfirm.value; + if (pin !== confirmVal) { + showToast('两次输入的密码不一致'); + triggerInputShake(unlockPinConfirm); + unlockPinConfirm.focus(); + return; + } + try { + window.pwdApi.setupMasterPin(pin); + showToast('主密码设置成功!'); + proceedAfterUnlock(); + } catch (err) { + showToast('初始化失败: ' + err.message); + } + } else { + const ok = window.pwdApi.unlock(pin); + if (ok) { + proceedAfterUnlock(); + } else { + showToast('主密码错误,请重试'); + triggerInputShake(unlockPin); + unlockPin.value = ''; + unlockPin.focus(); + } + } +} + +function proceedAfterUnlock(initialQuickQuery = '') { + if (currentTargetCode === 'pwd-quick-fill') { + switchView('quick', initialQuickQuery); + } else { + switchView('manager'); + } +} + +btnUnlockSubmit.addEventListener('click', handleUnlockOrSetup); +if (btnSkipMasterPin) { + btnSkipMasterPin.addEventListener('click', () => { + try { + window.pwdApi.setupWithoutMasterPin(); + syncMasterPinUiState(); + showToast('已开启免密使用,可随时在设置中开启主密码保护'); + proceedAfterUnlock(); + } catch (err) { + showToast('初始化失败: ' + err.message); + } + }); +} +unlockPin.addEventListener('keydown', (e) => { + if (e.key === 'Enter') { + if (window.pwdApi.isFirstRun()) { + unlockPinConfirm.focus(); + } else { + handleUnlockOrSetup(); + } + } +}); +unlockPinConfirm.addEventListener('keydown', (e) => { + if (e.key === 'Enter') { + handleUnlockOrSetup(); + } +}); + +// ======================= 核心功能:填充密码/账号 ======================= +/** + * 执行填充(带渲染层防重入保护) + * @param {string} id 条目 id + * @param {'both'|'username'|'password'} target 填充目标 + */ +async function fillPassword(id, target = 'both') { + if (isFillingInProgress) return; + isFillingInProgress = true; + + try { + const entry = window.pwdApi.getEntry(id); + if (!entry) { + showToast('未检索到该条目'); + return; + } + const username = (entry.username || '').trim(); + const needPwd = target !== 'username'; + + if (target === 'username' && !username) { + showToast('该条目未设置账号'); + return; + } + if (target === 'both' && !username) { + target = 'password'; + } + + const plainPwd = needPwd ? window.pwdApi.getPlainPwd(id) : ''; + if (needPwd && !plainPwd) { + showToast('未检索到密码内容'); + return; + } + + const config = window.pwdApi.getConfig(); + const fillMode = config.fillMode || 'paste'; + const isDetachedMode = isDetached(); + + const ztoolsObj = window.ztools || window.utools; + if (ztoolsObj) { + if (window.pwdApi && typeof window.pwdApi.autoFillCredentials === 'function') { + await window.pwdApi.autoFillCredentials({ + entryId: id, + username, + password: plainPwd, + mode: fillMode, + fillTarget: target, + isDetachedMode + }); + } + } else { + await copyTextSafe(needPwd ? plainPwd : username, needPwd); + showToast('环境不支持快捷填充,已复制到剪贴板'); + } + } catch (err) { + showToast('填充失败: ' + err.message); + } finally { + isFillingInProgress = false; + } +} + +// ======================= 快捷选密视图逻辑 ======================= +function getFillStrategy() { + try { + const config = window.pwdApi.getConfig(); + return config.fillStrategy || 'both'; + } catch (e) { + return 'both'; + } +} + +function getDefaultFillTarget(hasUser) { + if (!hasUser) return 'password'; + return getFillStrategy() === 'password_only' ? 'password' : 'both'; +} + +function updateQuickModeDisplay() { + const strategy = getFillStrategy(); + const isPwdOnly = strategy === 'password_only'; + if (btnQuickModeToggle) { + btnQuickModeToggle.textContent = isPwdOnly ? '回车: 仅密码' : '回车: 双填'; + btnQuickModeToggle.classList.toggle('is-pwd-only', isPwdOnly); + } + if (quickFooterPrimary) { + quickFooterPrimary.innerHTML = isPwdOnly + ? '↵ 仅填密码(光标放密码框)' + : '↵ 双填(光标放账号框)'; + } +} + +if (btnQuickModeToggle) { + btnQuickModeToggle.addEventListener('click', (e) => { + e.stopPropagation(); + const nextStrategy = getFillStrategy() === 'password_only' ? 'both' : 'password_only'; + window.pwdApi.setConfig({ fillStrategy: nextStrategy }); + updateQuickModeDisplay(); + renderQuickList(false); + quickFilterInput.focus(); + showToast(nextStrategy === 'password_only' ? '默认回车已切换为:仅填密码' : '默认回车已切换为:账号 + 密码'); + }); +} + +// 仅切换选中行高亮与滚动,避免键盘导航重读磁盘与重建 DOM +function updateQuickSelection() { + const items = quickList.querySelectorAll('.quick-item'); + items.forEach((el, idx) => { + el.classList.toggle('selected', idx === quickSelectedIndex); + }); + const selectedEl = items[quickSelectedIndex]; + if (selectedEl) { + selectedEl.scrollIntoView({ block: 'nearest' }); + } +} + +function renderQuickList(reloadFromDisk = true) { + if (reloadFromDisk || quickAllEntries.length === 0) { + quickAllEntries = window.pwdApi.listEntries(); + } + + const rawQuery = (quickFilterInput.value || '').trim(); + const tokens = parseSearchTokens(rawQuery); + const strategy = getFillStrategy(); + + filteredQuickItems = quickAllEntries.filter((item) => matchEntry(item, tokens)); + + if (quickSelectedIndex >= filteredQuickItems.length) { + quickSelectedIndex = Math.max(0, filteredQuickItems.length - 1); + } + + quickList.innerHTML = ''; + if (filteredQuickItems.length === 0) { + const emptyWrap = document.createElement('li'); + emptyWrap.className = 'quick-empty-wrap'; + emptyWrap.innerHTML = ` + 未匹配到密码条目 + ${rawQuery ? `` : ''} + `; + quickList.appendChild(emptyWrap); + const addBtn = emptyWrap.querySelector('#btn-quick-add-missing'); + if (addBtn) { + addBtn.addEventListener('click', () => { + switchView('manager'); + openAddModal(rawQuery); + }); + } + } else { + filteredQuickItems.forEach((item, index) => { + const hasUser = !!(item.username && item.username.trim()); + const defaultTarget = getDefaultFillTarget(hasUser); + const li = document.createElement('li'); + li.className = 'quick-item' + (index === quickSelectedIndex ? ' selected' : ''); + + const indexBadge = index < 9 ? `${index + 1}` : ''; + const pinBadge = item.pinned ? `${ICONS.starFilled}` : ''; + const labelHtml = highlightText(item.label, tokens); + const userHtml = hasUser ? `${highlightText(item.username, tokens)}` : ''; + const noteHtml = item.note ? `${highlightText(item.note, tokens)}` : ''; + + const isBothDefault = defaultTarget === 'both' && hasUser && strategy !== 'password_only'; + const isPwdDefault = defaultTarget === 'password'; + + li.innerHTML = ` +
+ ${indexBadge} + ${pinBadge} +
+ ${labelHtml} + ${userHtml} + ${noteHtml} +
+
+
+ + + +
+ `; + + li.querySelectorAll('.quick-action-btn').forEach((btn) => { + btn.addEventListener('click', (e) => { + e.stopPropagation(); + if (btn.classList.contains('disabled')) { + showToast('该条目未设置账号'); + return; + } + fillPassword(item.id, btn.dataset.target); + }); + }); + + li.addEventListener('click', () => { + quickSelectedIndex = index; + updateQuickSelection(); + fillPassword(item.id, defaultTarget); + }); + + quickList.appendChild(li); + }); + } + + // 动态调整窗口高度(包含顶栏 48px + 底栏 28px,最小 170,最大 480)仅在主窗口生效 + const rowsHeight = filteredQuickItems.length > 0 ? filteredQuickItems.length * 44 + 8 : 96; + const calculatedHeight = Math.min(480, Math.max(170, 76 + rowsHeight)); + safeSetExpendHeight(calculatedHeight); +} + +quickFilterInput.addEventListener('input', () => { + quickSelectedIndex = 0; + renderQuickList(false); +}); + +quickFilterInput.addEventListener('keydown', async (e) => { + if (e.key === 'ArrowDown') { + e.preventDefault(); + if (filteredQuickItems.length > 0) { + quickSelectedIndex = (quickSelectedIndex + 1) % filteredQuickItems.length; + updateQuickSelection(); + } + } else if (e.key === 'ArrowUp') { + e.preventDefault(); + if (filteredQuickItems.length > 0) { + quickSelectedIndex = (quickSelectedIndex - 1 + filteredQuickItems.length) % filteredQuickItems.length; + updateQuickSelection(); + } + } else if (e.key === 'Enter') { + e.preventDefault(); + const current = filteredQuickItems[quickSelectedIndex]; + if (current) { + const hasUser = !!(current.username && current.username.trim()); + let target = getDefaultFillTarget(hasUser); + if (e.shiftKey) target = 'password'; + else if (e.altKey && hasUser) target = 'username'; + fillPassword(current.id, target); + } + } else if ((e.ctrlKey || e.metaKey) && e.key.toLowerCase() === 'c') { + // 仅当搜索框没有选中文本时,Ctrl+C 才快捷复制当前高亮条目密码 + const hasSelection = quickFilterInput.selectionStart !== quickFilterInput.selectionEnd; + if (!hasSelection) { + const current = filteredQuickItems[quickSelectedIndex]; + if (current) { + e.preventDefault(); + try { + const plainPwd = window.pwdApi.getPlainPwd(current.id); + await copyTextSafe(plainPwd, true); + window.pwdApi.recordUsage(current.id); + const clearSec = window.pwdApi.getConfig().autoClearClipboardSeconds || 10; + showToast(`已复制 [${current.label}] 密码,${clearSec}s 后自动清空`); + } catch (err) { + showToast('复制密码失败: ' + err.message); + } + } + } + } else if (e.altKey && /^[1-9]$/.test(e.key)) { + const idx = parseInt(e.key, 10) - 1; + const item = filteredQuickItems[idx]; + if (item) { + e.preventDefault(); + quickSelectedIndex = idx; + updateQuickSelection(); + const hasUser = !!(item.username && item.username.trim()); + fillPassword(item.id, getDefaultFillTarget(hasUser)); + } + } else if (e.key === 'Escape') { + e.preventDefault(); + if (quickFilterInput.value) { + quickFilterInput.value = ''; + quickSelectedIndex = 0; + renderQuickList(false); + } else if (isDetached()) { + window.pwdApi.minimizeSelf(); + } else { + const ztoolsObj = window.ztools || window.utools; + if (ztoolsObj && typeof ztoolsObj.hideMainWindow === 'function') { + ztoolsObj.hideMainWindow(); + } + } + } +}); + +// ======================= 管理视图逻辑 ======================= +function renderManagerList() { + const tokens = parseSearchTokens(mgrSearchInput.value); + const allEntries = window.pwdApi.listEntries(); + const filtered = allEntries.filter((item) => matchEntry(item, tokens)); + + if (mgrCount) { + mgrCount.textContent = tokens.length > 0 ? `${filtered.length} / ${allEntries.length} 条` : `${allEntries.length} 条`; + } + + mgrTableBody.innerHTML = ''; + if (filtered.length === 0) { + mgrTableBody.innerHTML = ` + + + ${allEntries.length === 0 ? '暂无密码条目,点击右上角「+ 添加新密码」开始使用' : '未匹配到符合条件的密码条目'} + + + `; + return; + } + + filtered.forEach((item) => { + const tr = document.createElement('tr'); + const pinIconHtml = item.pinned ? ICONS.starFilled : ICONS.starOutline; + const hasUser = !!(item.username && item.username.trim()); + + tr.innerHTML = ` + +
+ ${item.pinned ? `${ICONS.starFilled}` : ''} + ${escapeHtml(item.label)} +
+ ${item.note ? `
${escapeHtml(item.note)}
` : ''} + + + ${hasUser + ? `${escapeHtml(item.username)}` + : '-'} + + ${formatDate(item.updatedAt)} + +
+ + + + + +
+ + `; + + const userCopyEl = tr.querySelector('.mgr-user-copy'); + if (userCopyEl) { + userCopyEl.addEventListener('click', async () => { + await copyTextSafe(item.username, false); + showToast('已复制账号'); + }); + } + + tr.querySelector('.btn-pin-action').addEventListener('click', () => { + try { + const pinned = window.pwdApi.togglePin(item.id); + renderManagerList(); + showToast(pinned ? '已置顶,快捷选密将优先展示' : '已取消置顶'); + } catch (err) { + showToast('操作失败: ' + err.message); + } + }); + + tr.querySelector('.btn-copy-pwd-action').addEventListener('click', async () => { + try { + const plain = window.pwdApi.getPlainPwd(item.id); + await copyTextSafe(plain, true); + window.pwdApi.recordUsage(item.id); + const clearSec = window.pwdApi.getConfig().autoClearClipboardSeconds || 10; + showToast(`密码已复制,${clearSec}s 后自动清空`); + } catch (err) { + showToast('复制失败: ' + err.message); + } + }); + + tr.querySelector('.btn-view-action').addEventListener('click', () => openViewModal(item.id)); + tr.querySelector('.btn-edit-action').addEventListener('click', () => openEditModal(item.id)); + tr.querySelector('.btn-del-action').addEventListener('click', () => handleDeleteEntry(item.id, item.label)); + + mgrTableBody.appendChild(tr); + }); +} + +mgrSearchInput.addEventListener('input', renderManagerList); + +// 打开新增密码弹窗 +function openAddModal(prefillLabel = '') { + entryId.value = ''; + modalEntryTitle.textContent = '添加新密码'; + entryLabel.value = prefillLabel; + entryUsername.value = ''; + entryPassword.value = ''; + entryPassword.type = 'password'; + entryPassword.placeholder = '请输入密码'; + entryNote.value = ''; + entryPwdRequired.style.display = 'inline'; + btnToggleEntryPwd.innerHTML = ICONS.eyeOpen; + updateEntryPasswordStrength(); + modalEntry.classList.add('active'); + setTimeout(() => { + if (prefillLabel) { + entryUsername.focus(); + } else { + entryLabel.focus(); + } + }, 30); +} + +btnAddEntry.addEventListener('click', () => openAddModal('')); + +// 编辑条目 +function openEditModal(id) { + const item = window.pwdApi.getEntry(id); + if (!item) return; + + entryId.value = item.id; + modalEntryTitle.textContent = '编辑密码条目'; + entryLabel.value = item.label; + entryUsername.value = item.username || ''; + entryPassword.value = ''; + entryPassword.type = 'password'; + entryPassword.placeholder = '留空表示不修改原密码'; + entryNote.value = item.note || ''; + entryPwdRequired.style.display = 'none'; + btnToggleEntryPwd.innerHTML = ICONS.eyeOpen; + updateEntryPasswordStrength(); + modalEntry.classList.add('active'); + setTimeout(() => entryLabel.focus(), 30); +} + +if (btnGenEntryPwd) { + btnGenEntryPwd.addEventListener('click', () => { + entryPassword.value = generateStrongPassword(16); + entryPassword.type = 'text'; + btnToggleEntryPwd.innerHTML = ICONS.eyeOff; + updateEntryPasswordStrength(); + entryPassword.focus(); + showToast('已生成 16 位随机强密码'); + }); +} + +entryPassword.addEventListener('input', updateEntryPasswordStrength); + +function saveEntryForm() { + const id = entryId.value; + const label = entryLabel.value.trim(); + const username = entryUsername.value.trim(); + const password = entryPassword.value; + const note = entryNote.value.trim(); + + if (!label) { + showToast('请输入平台/网站名称'); + entryLabel.focus(); + return; + } + + try { + if (!id) { + if (!password) { + showToast('请输入密码'); + entryPassword.focus(); + return; + } + window.pwdApi.addEntry(label, username, password, { note }); + showToast('条目已添加'); + } else { + window.pwdApi.updateEntry(id, label, username, password, { note }); + showToast('条目已更新'); + } + modalEntry.classList.remove('active'); + renderManagerList(); + } catch (err) { + showToast('保存失败: ' + err.message); + } +} + +btnSaveEntry.addEventListener('click', saveEntryForm); + +// 弹窗内键盘流畅流转与快捷保存 +entryLabel.addEventListener('keydown', (e) => { + if (e.key === 'Enter') { + e.preventDefault(); + entryUsername.focus(); + } +}); +entryUsername.addEventListener('keydown', (e) => { + if (e.key === 'Enter') { + e.preventDefault(); + entryPassword.focus(); + } +}); +entryPassword.addEventListener('keydown', (e) => { + if (e.key === 'Enter') { + e.preventDefault(); + saveEntryForm(); + } +}); +entryNote.addEventListener('keydown', (e) => { + if (e.key === 'Enter') { + e.preventDefault(); + saveEntryForm(); + } +}); + +btnCancelEntry.addEventListener('click', () => modalEntry.classList.remove('active')); +btnCloseEntryModal.addEventListener('click', () => modalEntry.classList.remove('active')); + +// 查看明文与详情 +function openViewModal(id) { + const item = window.pwdApi.getEntry(id); + if (!item) return; + + try { + const plain = window.pwdApi.getPlainPwd(id); + viewLabel.value = item.label; + viewUsername.value = item.username || '-'; + viewPlainPwd.value = plain; + if (item.note) { + viewNote.value = item.note; + viewNoteGroup.style.display = 'flex'; + } else { + viewNote.value = ''; + viewNoteGroup.style.display = 'none'; + } + modalViewPwd.classList.add('active'); + } catch (err) { + showToast('获取密码失败: ' + err.message); + } +} + +if (btnCopyViewUser) { + btnCopyViewUser.addEventListener('click', async () => { + const user = viewUsername.value; + if (!user || user === '-') { + showToast('该条目未设置账号'); + return; + } + await copyTextSafe(user, false); + showToast('账号已复制到剪贴板'); + }); +} + +btnCopyViewPwd.addEventListener('click', async () => { + const pwd = viewPlainPwd.value; + await copyTextSafe(pwd, true); + const clearSec = window.pwdApi.getConfig().autoClearClipboardSeconds || 10; + showToast(`密码已复制,${clearSec}s 后自动清空`); +}); + +btnCloseViewModal.addEventListener('click', () => modalViewPwd.classList.remove('active')); +btnCloseViewBtn.addEventListener('click', () => modalViewPwd.classList.remove('active')); + +// 删除条目(使用自定义确认框) +async function handleDeleteEntry(id, label) { + const confirmed = await showConfirmDialog({ + title: '删除密码条目', + message: `确定要删除 [${label}] 的密码记录吗?此操作无法撤回。`, + confirmText: '确认删除', + danger: true + }); + if (!confirmed) return; + + try { + window.pwdApi.deleteEntry(id); + showToast('已删除'); + renderManagerList(); + } catch (err) { + showToast('删除失败: ' + err.message); + } +} + +// 锁定保险库 +btnLockVault.addEventListener('click', () => { + window.pwdApi.lock(); + showToast('保险库已锁定'); + switchView('unlock'); +}); + +// ======================= 设置、主密码开关与导入导出 ======================= +btnOpenSettings.addEventListener('click', () => { + const config = window.pwdApi.getConfig(); + settingClearClipboard.value = config.autoClearClipboardSeconds || 10; + if (settingFillMode) settingFillMode.value = config.fillMode || 'paste'; + if (settingFillDelay) settingFillDelay.value = String(config.fillDelayMs || 450); + if (settingTabDelay) settingTabDelay.value = String(config.tabDelayMs || 180); + if (settingFillStrategy) settingFillStrategy.value = config.fillStrategy || 'both'; + if (settingAutoLock) settingAutoLock.value = String(config.autoLockMinutes || 0); + if (settingOpenStandalone) settingOpenStandalone.checked = config.openStandaloneByDefault === true; + syncMasterPinUiState(); + modalSettings.classList.add('active'); +}); + +// 实时切换主密码解锁保护开关 +if (settingRequirePin) { + settingRequirePin.addEventListener('change', async () => { + const wantEnable = settingRequirePin.checked; + if (!wantEnable) { + const confirmed = await showConfirmDialog({ + title: '关闭主密码解锁保护', + message: '关闭后,每次打开插件或重启 ZTools 将不再要求输入主密码 PIN。\n\n本地密码库仍保持加密存储,但能访问本机此账号的用户将可直接查看与填充密码。\n您随时可以在设置中重新开启。', + confirmText: '确认关闭', + danger: true + }); + if (!confirmed) { + settingRequirePin.checked = true; + return; + } + try { + window.pwdApi.disableMasterPin(); + syncMasterPinUiState(); + showToast('已关闭主密码解锁保护'); + } catch (err) { + settingRequirePin.checked = true; + showToast('关闭失败: ' + err.message); + } + } else { + openPinModal('enable'); + } + }); +} + +btnSaveSettings.addEventListener('click', () => { + const rawClearSec = parseInt(settingClearClipboard.value, 10) || 10; + const autoClearClipboardSeconds = Math.min(60, Math.max(3, rawClearSec)); + + window.pwdApi.setConfig({ + middleClickTrigger: false, + autoClearClipboardSeconds, + fillMode: settingFillMode ? settingFillMode.value : 'paste', + fillDelayMs: settingFillDelay ? (parseInt(settingFillDelay.value, 10) || 450) : 450, + tabDelayMs: settingTabDelay ? (parseInt(settingTabDelay.value, 10) || 180) : 180, + fillStrategy: settingFillStrategy ? settingFillStrategy.value : 'both', + autoLockMinutes: settingAutoLock ? (parseInt(settingAutoLock.value, 10) || 0) : 0, + openStandaloneByDefault: settingOpenStandalone ? settingOpenStandalone.checked : false + }); + + showToast('设置已保存'); + modalSettings.classList.remove('active'); +}); + +btnCloseSettingsModal.addEventListener('click', () => modalSettings.classList.remove('active')); + +// 打开修改/开启主密码弹窗 +function openPinModal(mode = 'change') { + pinModalMode = mode; + changeOldPin.value = ''; + changeNewPin.value = ''; + changeConfirmPin.value = ''; + + if (mode === 'enable') { + if (changePinTitle) changePinTitle.textContent = '开启主密码解锁保护'; + if (changeOldPinGroup) changeOldPinGroup.style.display = 'none'; + if (btnSubmitChangePin) btnSubmitChangePin.textContent = '开启并加密'; + modalChangePin.classList.add('active'); + setTimeout(() => changeNewPin.focus(), 30); + } else { + if (changePinTitle) changePinTitle.textContent = '修改主密码 PIN'; + if (changeOldPinGroup) changeOldPinGroup.style.display = 'flex'; + if (btnSubmitChangePin) btnSubmitChangePin.textContent = '确认修改'; + modalChangePin.classList.add('active'); + setTimeout(() => changeOldPin.focus(), 30); + } +} + +function closePinModal(cancelled = true) { + modalChangePin.classList.remove('active'); + if (cancelled && pinModalMode === 'enable') { + syncMasterPinUiState(); + } +} + +if (btnOpenChangePin) { + btnOpenChangePin.addEventListener('click', () => { + if (!window.pwdApi.isMasterPinRequired()) { + showToast('当前未开启主密码保护'); + return; + } + openPinModal('change'); + }); +} + +function submitChangePinForm() { + const oldPin = changeOldPin.value; + const newPin = changeNewPin.value; + const confirmPin = changeConfirmPin.value; + + if (pinModalMode === 'change' && !oldPin) { + showToast('请输入当前主密码'); + changeOldPin.focus(); + return; + } + if (!newPin || newPin.length < 4) { + showToast('新主密码长度不能少于 4 位'); + changeNewPin.focus(); + return; + } + if (newPin !== confirmPin) { + showToast('两次输入的新密码不一致'); + changeConfirmPin.focus(); + return; + } + + try { + if (pinModalMode === 'enable') { + window.pwdApi.enableMasterPin(newPin); + closePinModal(false); + syncMasterPinUiState(); + showToast('已开启主密码解锁保护并完成全库加密'); + } else { + window.pwdApi.changeMasterPin(oldPin, newPin); + closePinModal(false); + showToast('主密码已修改并完成全库重加密'); + } + } catch (err) { + showToast((pinModalMode === 'enable' ? '开启失败: ' : '修改失败: ') + err.message); + } +} + +if (btnSubmitChangePin) btnSubmitChangePin.addEventListener('click', submitChangePinForm); +if (changeConfirmPin) { + changeConfirmPin.addEventListener('keydown', (e) => { + if (e.key === 'Enter') submitChangePinForm(); + }); +} +if (btnCancelChangePin) btnCancelChangePin.addEventListener('click', () => closePinModal(true)); +if (btnCloseChangePinModal) btnCloseChangePinModal.addEventListener('click', () => closePinModal(true)); + +// 导出加密备份 +if (btnExportVault) { + btnExportVault.addEventListener('click', () => { + try { + const jsonStr = window.pwdApi.exportVaultJson(); + const blob = new Blob([jsonStr], { type: 'application/json;charset=utf-8' }); + const url = URL.createObjectURL(blob); + const a = document.createElement('a'); + const d = new Date(); + const pad = (n) => String(n).padStart(2, '0'); + const stamp = `${d.getFullYear()}${pad(d.getMonth() + 1)}${pad(d.getDate())}-${pad(d.getHours())}${pad(d.getMinutes())}`; + a.href = url; + a.download = `quick-pwd-backup-${stamp}.json`; + document.body.appendChild(a); + a.click(); + document.body.removeChild(a); + setTimeout(() => URL.revokeObjectURL(url), 1000); + const isPinOn = window.pwdApi.isMasterPinRequired(); + showToast(isPinOn ? '已导出加密备份文件' : '已导出备份文件(当前为免密模式,请妥善保管)'); + } catch (err) { + showToast('导出失败: ' + err.message); + } + }); +} + +// 导入加密备份 +if (btnImportVault && inputImportVault) { + btnImportVault.addEventListener('click', () => { + inputImportVault.value = ''; + inputImportVault.click(); + }); + + inputImportVault.addEventListener('change', async () => { + const file = inputImportVault.files && inputImportVault.files[0]; + if (!file) return; + + try { + const text = await file.text(); + const confirmed = await showConfirmDialog({ + title: '导入加密备份', + message: `确定要导入备份文件 "${file.name}" 吗?\n导入将覆盖当前密码库中的所有条目与主密码校验信息,建议导入前先导出当前备份。`, + confirmText: '确认覆盖导入', + danger: true + }); + if (!confirmed) return; + + const result = window.pwdApi.importVaultJson(text); + syncMasterPinUiState(); + modalSettings.classList.remove('active'); + if (result.unlocked) { + renderManagerList(); + showToast(`导入成功,共恢复 ${result.count} 条记录`); + } else { + showToast(`导入成功 (${result.count} 条),请用备份文件的主密码解锁`); + switchView('unlock'); + } + } catch (err) { + showToast('导入失败: ' + err.message); + } + }); +} + +// 使用手册对话框 +if (btnOpenGuide) { + btnOpenGuide.addEventListener('click', () => { + if (modalGuide) modalGuide.classList.add('active'); + }); +} +if (btnCloseGuideModal) { + btnCloseGuideModal.addEventListener('click', () => { + if (modalGuide) modalGuide.classList.remove('active'); + }); +} +if (btnCloseGuideBtn) { + btnCloseGuideBtn.addEventListener('click', () => { + if (modalGuide) modalGuide.classList.remove('active'); + }); +} + +// 点击遮罩空白区域关闭弹窗 +document.querySelectorAll('.modal-overlay').forEach((overlay) => { + overlay.addEventListener('click', (e) => { + if (e.target === overlay) { + if (overlay === modalConfirm) { + closeConfirmDialog(false); + } else if (overlay === modalChangePin) { + closePinModal(true); + } else { + overlay.classList.remove('active'); + } + } + }); +}); + +// 全局 ESC / 弹窗快捷键监听 +window.addEventListener('keydown', (e) => { + if (e.key === 'Escape') { + if (modalConfirm.classList.contains('active')) { + e.preventDefault(); + e.stopPropagation(); + closeConfirmDialog(false); + return; + } + const activeModals = Array.from(document.querySelectorAll('.modal-overlay.active')); + if (activeModals.length > 0) { + e.preventDefault(); + e.stopPropagation(); + const topModal = activeModals[activeModals.length - 1]; + if (topModal === modalChangePin) { + closePinModal(true); + } else { + topModal.classList.remove('active'); + } + } + } else if (e.key === 'Enter' && modalConfirm.classList.contains('active')) { + e.preventDefault(); + e.stopPropagation(); + closeConfirmDialog(true); + } else if ((e.ctrlKey || e.metaKey) && e.key === 'Enter' && modalEntry.classList.contains('active')) { + e.preventDefault(); + saveEntryForm(); + } +}); + +// 快捷选密界面点击打开独立管理器按钮 +if (btnQuickOpenMgr) { + btnQuickOpenMgr.addEventListener('click', (e) => { + e.stopPropagation(); + if (window.pwdApi && typeof window.pwdApi.openManagerWindow === 'function') { + window.pwdApi.openManagerWindow(); + const ztoolsObj = window.ztools || window.utools; + if (ztoolsObj && typeof ztoolsObj.outPlugin === 'function') { + try { ztoolsObj.outPlugin(); } catch (err) {} + } else if (ztoolsObj && typeof ztoolsObj.hideMainWindow === 'function') { + try { ztoolsObj.hideMainWindow(false); } catch (err) {} + } + } + }); +} + +// 主管理界面标题栏“独立窗口打开”按钮 +if (btnDetachWindow) { + btnDetachWindow.addEventListener('click', () => { + if (window.pwdApi && typeof window.pwdApi.openManagerWindow === 'function') { + window.pwdApi.openManagerWindow(); + const ztoolsObj = window.ztools || window.utools; + if (ztoolsObj && typeof ztoolsObj.outPlugin === 'function') { + try { ztoolsObj.outPlugin(); } catch (err) {} + } else if (ztoolsObj && typeof ztoolsObj.hideMainWindow === 'function') { + try { ztoolsObj.hideMainWindow(false); } catch (err) {} + } + } + }); +} + +// 跨窗口 IPC 消息监听与同步 +if (window.pwdApi && typeof window.pwdApi.onWindowMessage === 'function') { + // 1. 独立窗口接收主窗口指令(携带 payload 快速定位搜索) + window.pwdApi.onWindowMessage('plugin-action', (action) => { + if (action && action.payload && typeof action.payload === 'string') { + const q = action.payload.trim(); + if (q) { + if (mgrSearchInput) { + mgrSearchInput.value = q; + } + if (viewManager.classList.contains('active')) { + renderManagerList(); + } + } + } + }); + + // 2. 凭据同步(一处解锁,跨窗口同时解锁) + window.pwdApi.onWindowMessage('sync-auth', () => { + if (viewUnlock.classList.contains('active')) { + proceedAfterUnlock(); + } + }); + + // 3. 锁定同步(一处锁定,跨窗口同时锁定) + window.pwdApi.onWindowMessage('sync-lock', () => { + switchView('unlock'); + }); + + // 4. 数据更新同步(添加/修改/删除/统计更新时自动刷新缓存与列表) + window.pwdApi.onWindowMessage('data-updated', () => { + quickAllEntries = window.pwdApi.listEntries(); + if (viewManager.classList.contains('active')) { + renderManagerList(); + } else if (viewQuick.classList.contains('active')) { + renderQuickList(false); + } + }); + + // 5. 配置更新同步(主密码保护状态跨窗口同步) + window.pwdApi.onWindowMessage('config-updated', () => { + syncMasterPinUiState(); + }); +} + +// 提取可作为过滤词的入口 payload(排除插件自身触发指令词) +function extractQuickInitialQuery(action) { + if (!action || typeof action.payload !== 'string') return ''; + const trimmed = action.payload.trim(); + if (!trimmed || QUICK_TRIGGER_CMDS.has(trimmed.toLowerCase())) { + return ''; + } + return trimmed; +} + +// ======================= ZTools 入口与生命周期 ======================= +if (typeof ztools !== 'undefined' && typeof ztools.onPluginEnter === 'function') { + ztools.onPluginEnter((action) => { + // 1. 设置深色模式跟随系统 + if (typeof ztools.isDarkColors === 'function' && ztools.isDarkColors()) { + document.documentElement.classList.add('dark'); + } else { + document.documentElement.classList.remove('dark'); + } + + const winMode = getWindowMode(); + const targetCode = action.code || 'pwd-manager'; + const initialQuickQuery = targetCode === 'pwd-quick-fill' ? extractQuickInitialQuery(action) : ''; + + // 2. 如果当前处于独立窗口中(包括 createBrowserWindow 与 Ctrl+D 分离窗口) + if (winMode === 'detach' || winMode === 'browser') { + if (window.pwdApi && typeof window.pwdApi.bringToFront === 'function') { + window.pwdApi.bringToFront(); + } else { + window.focus(); + } + + currentTargetCode = targetCode; + if (targetCode !== 'pwd-quick-fill' && action.payload && typeof action.payload === 'string') { + const q = action.payload.trim(); + if (q && mgrSearchInput) { + mgrSearchInput.value = q; + } + } + + if (!window.pwdApi.isUnlocked()) { + switchView('unlock'); + } else { + proceedAfterUnlock(initialQuickQuery); + } + return; + } + + // 3. 只有当用户主动在设置中开启了“默认以独立桌面窗口打开”,才自动弹开独立窗口 + const config = window.pwdApi.getConfig(); + if (winMode === 'main' && targetCode === 'pwd-manager' && config.openStandaloneByDefault === true) { + if (window.pwdApi && typeof window.pwdApi.openManagerWindow === 'function') { + const ok = window.pwdApi.openManagerWindow(action); + if (ok) { + if (typeof ztools.outPlugin === 'function') { + try { ztools.outPlugin(); } catch (e) {} + } else if (typeof ztools.hideMainWindow === 'function') { + try { ztools.hideMainWindow(false); } catch (e) {} + } + return; + } + } + } + + // 4. 常规正常主窗口流程 + currentTargetCode = targetCode; + if (!window.pwdApi.isUnlocked()) { + switchView('unlock'); + } else { + proceedAfterUnlock(initialQuickQuery); + } + }); + + // 监听插件分离为独立窗口事件 + if (typeof ztools.onPluginDetach === 'function') { + ztools.onPluginDetach(() => { + startStandaloneHeartbeat(); + if (window.pwdApi && typeof window.pwdApi.bringToFront === 'function') { + window.pwdApi.bringToFront(); + } + }); + } +} + +// 独立窗口 (BrowserWindow) 或纯浏览器调试环境的自启动生命周期 +window.addEventListener('DOMContentLoaded', () => { + const winMode = getWindowMode(); + if (winMode === 'browser' || winMode === 'detach') { + const ztoolsObj = window.ztools || window.utools; + if (ztoolsObj && typeof ztoolsObj.isDarkColors === 'function' && ztoolsObj.isDarkColors()) { + document.documentElement.classList.add('dark'); + } + if (window.pwdApi && !window.pwdApi.isUnlocked()) { + switchView('unlock'); + } else { + switchView('manager'); + } + } else if (typeof ztools === 'undefined') { + if (window.pwdApi && !window.pwdApi.isUnlocked()) { + switchView('unlock'); + } else { + switchView('manager'); + } + } +}); diff --git a/plugins/ztools-quick-pwd/libs/crypto.js b/plugins/ztools-quick-pwd/libs/crypto.js new file mode 100644 index 000000000..c9afe1a7b --- /dev/null +++ b/plugins/ztools-quick-pwd/libs/crypto.js @@ -0,0 +1,89 @@ +const crypto = require('crypto'); + +/** + * PBKDF2 派生主密钥 + * @param {string} pin 用户输入的 PIN 或主密码 + * @param {string} saltHex 16进制盐字符串 + * @param {number} iterations 迭代次数,默认 100,000 + * @returns {Buffer} 32 字节 masterKey + */ +function deriveMasterKey(pin, saltHex, iterations = 100000) { + if (!pin || typeof pin !== 'string') { + throw new Error('PIN 码不能为空且必须是字符串'); + } + if (!saltHex || typeof saltHex !== 'string') { + throw new Error('Salt 不能为空且必须是十六进制字符串'); + } + const salt = Buffer.from(saltHex, 'hex'); + return crypto.pbkdf2Sync(pin, salt, iterations, 32, 'sha256'); +} + +/** + * 生成 32 字节随机盐 + * @returns {string} 64 位十六进制字符串 + */ +function generateSalt() { + return crypto.randomBytes(32).toString('hex'); +} + +/** + * AES-256-GCM 加密明文 + * @param {Buffer} masterKey 32 字节 Buffer + * @param {string} plainText 明文字符串 + * @returns {{ iv: string, tag: string, data: string }} 十六进制编码的对象 + */ +function encrypt(masterKey, plainText) { + if (!Buffer.isBuffer(masterKey) || masterKey.length !== 32) { + throw new Error('非法的 MasterKey,必须为 32 字节 Buffer'); + } + const iv = crypto.randomBytes(12); // 96-bit IV 推荐用于 GCM + const cipher = crypto.createCipheriv('aes-256-gcm', masterKey, iv); + + const encrypted = Buffer.concat([ + cipher.update(String(plainText), 'utf8'), + cipher.final() + ]); + const tag = cipher.getAuthTag(); + + return { + iv: iv.toString('hex'), + tag: tag.toString('hex'), + data: encrypted.toString('hex') + }; +} + +/** + * AES-256-GCM 解密密文 + * @param {Buffer} masterKey 32 字节 Buffer + * @param {{ iv: string, tag: string, data: string }} cipherObj + * @returns {string} 解密后的明文字符串 + */ +function decrypt(masterKey, cipherObj) { + if (!Buffer.isBuffer(masterKey) || masterKey.length !== 32) { + throw new Error('非法的 MasterKey,必须为 32 字节 Buffer'); + } + if (!cipherObj || !cipherObj.iv || !cipherObj.tag || cipherObj.data === undefined) { + throw new Error('密文对象格式不正确'); + } + + const iv = Buffer.from(cipherObj.iv, 'hex'); + const tag = Buffer.from(cipherObj.tag, 'hex'); + const encrypted = Buffer.from(cipherObj.data, 'hex'); + + const decipher = crypto.createDecipheriv('aes-256-gcm', masterKey, iv); + decipher.setAuthTag(tag); + + const decrypted = Buffer.concat([ + decipher.update(encrypted), + decipher.final() + ]); + + return decrypted.toString('utf8'); +} + +module.exports = { + deriveMasterKey, + generateSalt, + encrypt, + decrypt +}; diff --git a/plugins/ztools-quick-pwd/libs/mouse-hook.js b/plugins/ztools-quick-pwd/libs/mouse-hook.js new file mode 100644 index 000000000..26fb0b4e3 --- /dev/null +++ b/plugins/ztools-quick-pwd/libs/mouse-hook.js @@ -0,0 +1,193 @@ +const { spawn } = require('child_process'); +const path = require('path'); +const os = require('os'); + +let psProcess = null; +let isStopping = false; + +/** + * 启动鼠标中键长按监听(目前支持 Windows 环境) + * @param {object} options + * @param {number} [options.holdDurationMs=500] 判定长按的毫秒数 + * @param {function} [options.onTrigger] 触发回调 (x, y) + * @param {function} [options.onError] 错误回调 + */ +function start(options = {}) { + const platform = os.platform(); + if (platform !== 'win32' && platform !== 'linux') { + // macOS 系统沙盒机制限制未授权子进程全局监听,建议使用 ZTools 原生超级面板或全局快捷键 + console.info('[mouse-hook] macOS 平台已原生集成 ZTools 超级面板与全局热键,无需额外脚本'); + return false; + } + + if (psProcess) { + return true; // 已经运行中 + } + + const holdMs = (options && options.holdDurationMs) || 500; + isStopping = false; + if (platform === 'win32') { + return startWindows(options, holdMs); + } else if (platform === 'linux') { + return startLinux(options, holdMs); + } + return false; +} + +function startWindows(options, holdMs) { + const scriptPath = path.join(__dirname, '..', 'scripts', 'mid-btn-watch.ps1'); + const args = [ + '-NoProfile', + '-NonInteractive', + '-ExecutionPolicy', 'Bypass', + '-File', scriptPath, + '-HoldDurationMs', String(holdMs) + ]; + + try { + psProcess = spawn('powershell.exe', args, { + windowsHide: true, + stdio: ['ignore', 'pipe', 'pipe'] + }); + + let buffer = ''; + + psProcess.stdout.on('data', (chunk) => { + buffer += chunk.toString('utf8'); + const lines = buffer.split(/\r?\n/); + buffer = lines.pop(); + + for (const line of lines) { + const trimmed = line.trim(); + if (trimmed.startsWith('TRIGGER')) { + const parts = trimmed.split(' '); + let x = 0, y = 0; + if (parts.length > 1) { + const coords = parts[1].split(','); + x = parseInt(coords[0], 10) || 0; + y = parseInt(coords[1], 10) || 0; + } + if (typeof options.onTrigger === 'function') { + try { + options.onTrigger(x, y); + } catch (cbErr) { + console.error('[mouse-hook] onTrigger 异常:', cbErr); + } + } + } + } + }); + + psProcess.stderr.on('data', (chunk) => { + const errStr = chunk.toString('utf8').trim(); + if (errStr && !isStopping) { + console.error('[mouse-hook] Windows stderr:', errStr); + if (typeof options.onError === 'function') { + options.onError(errStr); + } + } + }); + + psProcess.on('exit', () => { psProcess = null; }); + psProcess.on('error', (err) => { + console.error('[mouse-hook] Windows powershell 异常:', err); + psProcess = null; + }); + + return true; + } catch (err) { + console.error('[mouse-hook] 启动 powershell 失败:', err); + psProcess = null; + return false; + } +} + +/** + * Linux X11 环境监听(基于 xinput) + */ +function startLinux(options, holdMs) { + try { + // 监听 X11 根窗口的所有输入事件 + psProcess = spawn('xinput', ['test-xi2', '--root'], { + stdio: ['ignore', 'pipe', 'pipe'] + }); + + let pressTimer = null; + let isPressed = false; + let buffer = ''; + + psProcess.stdout.on('data', (chunk) => { + buffer += chunk.toString('utf8'); + const lines = buffer.split(/\r?\n/); + buffer = lines.pop(); + + for (const line of lines) { + // xinput 事件:EVENT type 15 (ButtonPress) / EVENT type 16 (ButtonRelease) + // 鼠标中键通常是 detail: 2 + if (line.includes('EVENT type 15 (ButtonPress)')) { + isPressed = true; + } else if (line.includes('EVENT type 16 (ButtonRelease)')) { + isPressed = false; + if (pressTimer) { + clearTimeout(pressTimer); + pressTimer = null; + } + } else if (isPressed && line.includes('detail: 2')) { + // 确认是中键按下,启动长按计时 + if (!pressTimer) { + pressTimer = setTimeout(() => { + if (isPressed && typeof options.onTrigger === 'function') { + try { + options.onTrigger(0, 0); + } catch (e) { + console.error('[mouse-hook] Linux onTrigger 异常:', e); + } + } + pressTimer = null; + }, holdMs); + } + } + } + }); + + psProcess.stderr.on('data', () => {}); + psProcess.on('exit', () => { psProcess = null; }); + psProcess.on('error', (err) => { + console.warn('[mouse-hook] Linux xinput 未安装或非 X11 环境,请使用 ZTools 原生超级面板或快捷键'); + psProcess = null; + }); + + return true; + } catch (e) { + console.warn('[mouse-hook] 启动 Linux xinput 失败:', e.message); + psProcess = null; + return false; + } +} + +/** + * 停止鼠标中键监听进程 + */ +function stop() { + if (!psProcess) return; + isStopping = true; + try { + psProcess.kill('SIGTERM'); + } catch (e) { + // 忽略 + } + psProcess = null; +} + +/** + * 是否正在监听 + */ +function isRunning() { + return !!psProcess; +} + +module.exports = { + start, + stop, + isRunning +}; diff --git a/plugins/ztools-quick-pwd/libs/store.js b/plugins/ztools-quick-pwd/libs/store.js new file mode 100644 index 000000000..8592bbbe3 --- /dev/null +++ b/plugins/ztools-quick-pwd/libs/store.js @@ -0,0 +1,137 @@ +const fs = require('fs'); +const path = require('path'); +const crypto = require('crypto'); + +let vaultFilePath = ''; + +/** + * 初始化存储路径 + * @param {string} userDataPath ZTools 用户数据目录 + */ +function init(userDataPath) { + const dir = path.join(userDataPath, 'ztools-quick-pwd'); + if (!fs.existsSync(dir)) { + fs.mkdirSync(dir, { recursive: true }); + } + vaultFilePath = path.join(dir, 'vault.json'); +} + +/** + * 生成唯一 ID + * @returns {string} + */ +function newId() { + return crypto.randomUUID ? crypto.randomUUID() : crypto.randomBytes(16).toString('hex'); +} + +/** + * 默认空的 vault 结构 + */ +function getDefaultVault() { + return { + version: 1, + salt: null, + verifyToken: null, + autoUnlockKey: null, + entries: [], + config: { + middleClickTrigger: false, + autoClearClipboardSeconds: 10, + holdDurationMs: 500, + fillMode: 'paste', + fillDelayMs: 450, + tabDelayMs: 180, + fillStrategy: 'both', + openStandaloneByDefault: false, + autoLockMinutes: 0, + requireMasterPin: true + } + }; +} + +/** + * 读取 vault.json + * @returns {object} + */ +function load() { + if (!vaultFilePath) { + throw new Error('Store 尚未初始化,请先调用 init(userDataPath)'); + } + const defaults = getDefaultVault(); + if (!fs.existsSync(vaultFilePath)) { + return defaults; + } + try { + const raw = fs.readFileSync(vaultFilePath, 'utf8'); + const data = JSON.parse(raw); + const rawConfig = data.config || {}; + const parsedTabDelay = parseInt(rawConfig.tabDelayMs, 10); + const parsedAutoLock = parseInt(rawConfig.autoLockMinutes, 10); + + return { + version: data.version || 1, + salt: data.salt || null, + verifyToken: data.verifyToken || null, + autoUnlockKey: (typeof data.autoUnlockKey === 'string' && data.autoUnlockKey.length > 0) ? data.autoUnlockKey : null, + entries: Array.isArray(data.entries) ? data.entries : [], + config: Object.assign({}, defaults.config, rawConfig, { + middleClickTrigger: false, + tabDelayMs: Number.isFinite(parsedTabDelay) && parsedTabDelay > 0 ? parsedTabDelay : defaults.config.tabDelayMs, + autoLockMinutes: Number.isFinite(parsedAutoLock) && parsedAutoLock >= 0 ? parsedAutoLock : defaults.config.autoLockMinutes, + fillStrategy: rawConfig.fillStrategy || defaults.config.fillStrategy, + openStandaloneByDefault: rawConfig.openStandaloneByDefault === true, + requireMasterPin: rawConfig.requireMasterPin !== false + }) + }; + } catch (err) { + console.error('读取 vault.json 失败:', err); + return defaults; + } +} + +/** + * 原子化保存 vault.json + * 先写入临时文件,再原子替换原文件 + * @param {object} vault + */ +function save(vault) { + if (!vaultFilePath) { + throw new Error('Store 尚未初始化,请先调用 init(userDataPath)'); + } + const dir = path.dirname(vaultFilePath); + if (!fs.existsSync(dir)) { + fs.mkdirSync(dir, { recursive: true }); + } + + const tmpPath = path.join(dir, `vault.tmp.${Date.now()}.${Math.random().toString(36).substring(2, 8)}`); + const jsonStr = JSON.stringify(vault, null, 2); + + fs.writeFileSync(tmpPath, jsonStr, 'utf8'); + try { + fs.renameSync(tmpPath, vaultFilePath); + } catch (err) { + // 兼容 Windows 下同名覆盖异常,先尝试删除目标文件 + if (err.code === 'EEXIST' || err.code === 'EPERM') { + try { + fs.unlinkSync(vaultFilePath); + fs.renameSync(tmpPath, vaultFilePath); + } catch (innerErr) { + fs.unlinkSync(tmpPath); + throw innerErr; + } + } else { + if (fs.existsSync(tmpPath)) { + fs.unlinkSync(tmpPath); + } + throw err; + } + } +} + +module.exports = { + init, + load, + save, + newId, + getDefaultVault +}; diff --git a/plugins/ztools-quick-pwd/logo.png b/plugins/ztools-quick-pwd/logo.png new file mode 100644 index 0000000000000000000000000000000000000000..a172c2284731d96ca9d6db475c95c45962c8ac89 GIT binary patch literal 1318 zcmW+$eN0nV6hAF3lq&Y2APg$4;08JojE0dhc}4Jpg%2?b#t*2QjA7M+&MNYJeFCP% zI$VTAS(N$_!;sD5B2%NZWfYi0A^ zc{Eu*t}&Ar))MWE=kco=irK=*4z86D8SYlqZd1rf-TT(99Md5mJdEbr{mOTRvgjex zsoV&l&v!cNxDw(fom3czS&q7Ub5p={=9uNl)cjxL!FK0VK`79L)*`l8ztk-qXyU2k z1UL>hO?#iOgveozfGI>}c_5&ejm|p*(GfHD30tc=E(D*Ae$o@5j+=w~Q%oei8DTX# z*3+keeIsTgOM%r?{< z2*$&yR3`JB47skc_Sv_$XS2l~S70KgLuW>y7(tbbSeW7ILi=Px6$?}Tk=iL>OS*J( zse7pnuUOLIMs|tF@b^6ZXr!^j(G2l)W7%ITdhA1AvnXpbs0*g5TnM0#0G>Vv0`&KH z1_6&$I*LL8BVF^e%izJ?`#E8N>G?3*vXpx9Y-F(j{P18ZiOF~QW~b^(>xF!Bx)_5w zq^t3KDFoc@dOnxLC>fI=puEZZYcH&TQ1E)l5_{&{u5HEUaLW zo=-8~&>A1Hp6Bk*$wwVrsSTi*OU_DgN9m>BSDFsdg8#yiP)?(2i1jOpSY)X~)OLRs zdg^S23M8!%Ln6|gT8=cgqZ8MLP!TM;a~OHB6uPTfoItE#8TlnbsN_ME(yQw=5~7|d z<(STBv}qFJI#WNRPc#7b(+?3khMe+F2fMQ#Q_H!Y!Qt^5W|n7_<#Ci}50m-P?Z;0T V%kZ7jeU9cIq_4?JyS7?d@jq&qPmKTo literal 0 HcmV?d00001 diff --git a/plugins/ztools-quick-pwd/plugin.json b/plugins/ztools-quick-pwd/plugin.json new file mode 100644 index 000000000..d071b3a7c --- /dev/null +++ b/plugins/ztools-quick-pwd/plugin.json @@ -0,0 +1,29 @@ +{ + "name": "ztools-quick-pwd", + "pluginName": "ztools-quick-pwd", + "title": "快速密码填充", + "description": "本地 AES-256-GCM 加密存储密码,长按鼠标中键或快捷指令一键将密码填入当前光标所在输入框", + "version": "0.0.1", + "author": "wangtao", + "homepage": "https://github.com", + "main": "index.html", + "logo": "logo.png", + "preload": "preload.js", + "categories": ["productivity"], + "platform": ["win32", "darwin", "linux"], + "pluginSetting": { + "single": false + }, + "features": [ + { + "code": "pwd-manager", + "explain": "打开密码管理器", + "cmds": ["密码", "pwd", "填密", "密码管理", "password"] + }, + { + "code": "pwd-quick-fill", + "explain": "快速选择并填充密码", + "cmds": ["填密码", "快速填充", "quick pwd"] + } + ] +} diff --git a/plugins/ztools-quick-pwd/preload.js b/plugins/ztools-quick-pwd/preload.js new file mode 100644 index 000000000..e004e6ead --- /dev/null +++ b/plugins/ztools-quick-pwd/preload.js @@ -0,0 +1,1370 @@ +const fs = require('fs'); +const path = require('path'); +const os = require('os'); +const crypto = require('crypto'); +const store = require('./libs/store'); +const cryptoLib = require('./libs/crypto'); +const mouseHook = require('./libs/mouse-hook'); + +let nativeAddon = null; +function getNativeAddon() { + if (nativeAddon) return nativeAddon; + const platform = os.platform(); + const sub = platform === 'darwin' ? 'mac' : 'win'; + const fileName = 'ztools_native.node'; + + const candidates = [ + process.resourcesPath ? path.join(process.resourcesPath, 'app.asar.unpacked', 'resources', 'lib', sub, fileName) : null, + process.resourcesPath ? path.join(process.resourcesPath, 'resources', 'lib', sub, fileName) : null, + process.env.LOCALAPPDATA ? path.join(process.env.LOCALAPPDATA, 'Programs', 'ZTools', 'resources', 'app.asar.unpacked', 'resources', 'lib', sub, fileName) : null, + platform === 'win32' ? path.join(os.homedir(), 'AppData', 'Local', 'Programs', 'ZTools', 'resources', 'app.asar.unpacked', 'resources', 'lib', sub, fileName) : null, + path.join(__dirname, '..', '..', 'resources', 'lib', sub, fileName), + path.join(__dirname, '..', '..', '..', 'ZTools', 'resources', 'lib', sub, fileName) + ].filter(Boolean); + + for (const p of candidates) { + try { + if (fs.existsSync(p)) { + nativeAddon = require(p); + break; + } + } catch (e) {} + } + return nativeAddon; +} + +// 获取当前运行的 ZTools / uTools API 对象 +function getZTools() { + if (typeof window !== 'undefined') { + if (window.ztools) return window.ztools; + if (window.utools) return window.utools; + } + if (typeof globalThis !== 'undefined') { + if (globalThis.ztools) return globalThis.ztools; + if (globalThis.utools) return globalThis.utools; + } + if (typeof ztools !== 'undefined') return ztools; + if (typeof utools !== 'undefined') return utools; + return null; +} + +let electron = null; +try { + electron = require('electron'); +} catch (e) {} + +// 内存中缓存的主密钥 Buffer(插件锁定时置 null) +let cachedMasterKey = null; + +// 全局独立窗口引用(单例持久化) +let standaloneWindow = null; + +// 模块级状态与防重入锁 +let isAutoFilling = false; +let clearClipboardTimer = null; +let lastSensitiveClipboard = null; +let lastActivityAt = Date.now(); +let autoLockCheckInterval = null; + +// 延时工具 +function sleep(ms) { + return new Promise((resolve) => setTimeout(resolve, ms)); +} + +// 安全读取当前系统剪贴板文本(失败或不支持时返回 null) +function readClipboardSafe() { + if (electron && electron.clipboard && typeof electron.clipboard.readText === 'function') { + try { + return electron.clipboard.readText(); + } catch (e) {} + } + return null; +} + +/** + * 单一通道、带回读校验的可靠剪贴板写入 + * 严禁并发调用多个写剪贴板接口,杜绝异步竞态导致内容覆盖或乱序 + */ +async function writeClipboardReliable(text) { + const targetText = String(text ?? ''); + const z = getZTools(); + + // 通道 1(首选):使用 Electron 原生剪贴板,写入后立即回读校验是否真正落盘 + if (electron && electron.clipboard && typeof electron.clipboard.writeText === 'function') { + for (let attempt = 0; attempt < 5; attempt++) { + try { + electron.clipboard.writeText(targetText); + if (typeof electron.clipboard.readText === 'function') { + if (electron.clipboard.readText() === targetText) { + return true; + } + } else { + await sleep(30); + return true; + } + } catch (e) {} + await sleep(15); + } + } + + // 通道 2(降级):ZTools 官方 copyText + if (z && typeof z.copyText === 'function') { + try { + z.copyText(targetText); + await sleep(50); + return true; + } catch (e) {} + } + + // 通道 3(纯浏览器兜底):必须 await 异步落盘 + if (typeof navigator !== 'undefined' && navigator.clipboard && typeof navigator.clipboard.writeText === 'function') { + try { + await navigator.clipboard.writeText(targetText); + return true; + } catch (e) {} + } + + return false; +} + +// 取消待执行的敏感剪贴板清理定时器 +function cancelClipboardClear() { + if (clearClipboardTimer) { + clearTimeout(clearClipboardTimer); + clearClipboardTimer = null; + } + lastSensitiveClipboard = null; +} + +// 执行一次智能剪贴板清理(仅当剪贴板内容未变化或无法回读时才清空) +async function performSmartClipboardClear(expectedSecret) { + const current = readClipboardSafe(); + if (current !== null && current !== expectedSecret) { + return false; + } + await writeClipboardReliable(''); + return true; +} + +// 计划在指定秒数后安全清理剪贴板中的敏感密码 +function scheduleClipboardClear(secretText, seconds) { + cancelClipboardClear(); + if (!secretText) return; + const safeSeconds = Math.max(3, parseInt(seconds, 10) || 10); + lastSensitiveClipboard = secretText; + clearClipboardTimer = setTimeout(() => { + const expected = lastSensitiveClipboard; + clearClipboardTimer = null; + lastSensitiveClipboard = null; + if (expected) { + performSmartClipboardClear(expected).catch(() => {}); + } + }, safeSeconds * 1000); +} + +// 启动空闲自动锁定检查定时器 +function ensureAutoLockMonitor() { + if (autoLockCheckInterval) return; + autoLockCheckInterval = setInterval(() => { + try { + if (!cachedMasterKey) return; + const vault = store.load(); + if (vault?.config?.requireMasterPin === false) return; + const autoLockMinutes = parseInt(vault?.config?.autoLockMinutes, 10) || 0; + if (autoLockMinutes > 0) { + const idleMs = Date.now() - lastActivityAt; + if (idleMs >= autoLockMinutes * 60 * 1000) { + pwdApi.lock(); + } + } + } catch (e) {} + }, 30 * 1000); + if (typeof autoLockCheckInterval.unref === 'function') { + autoLockCheckInterval.unref(); + } +} + +// 免密模式下自动恢复内存主密钥 +function tryAutoUnlock() { + if (cachedMasterKey) return true; + try { + const vault = store.load(); + if ( + vault && + vault.config && + vault.config.requireMasterPin === false && + typeof vault.autoUnlockKey === 'string' && + /^[0-9a-fA-F]{64}$/.test(vault.autoUnlockKey) && + isValidCipherObj(vault.verifyToken) + ) { + const autoKey = Buffer.from(vault.autoUnlockKey, 'hex'); + const plain = cryptoLib.decrypt(autoKey, vault.verifyToken); + if (plain === 'VALID_MASTER_TOKEN') { + cachedMasterKey = autoKey; + lastActivityAt = Date.now(); + return true; + } + } + } catch (e) {} + return false; +} + +// 脱敏转换与智能排序(置顶优先 -> 最近使用 -> 最近更新 -> 最近创建) +function toSafeEntry(item) { + return { + id: item.id, + label: item.label, + username: item.username || '', + note: item.note || '', + pinned: !!item.pinned, + lastUsedAt: item.lastUsedAt || 0, + useCount: item.useCount || 0, + createdAt: item.createdAt || 0, + updatedAt: item.updatedAt || 0 + }; +} + +function sortEntries(entries) { + return entries.slice().sort((a, b) => { + const pinDiff = (b.pinned ? 1 : 0) - (a.pinned ? 1 : 0); + if (pinDiff !== 0) return pinDiff; + const usedDiff = (b.lastUsedAt || 0) - (a.lastUsedAt || 0); + if (usedDiff !== 0) return usedDiff; + const updDiff = (b.updatedAt || 0) - (a.updatedAt || 0); + if (updDiff !== 0) return updDiff; + return (b.createdAt || 0) - (a.createdAt || 0); + }); +} + +// 初始化存储 +const zObj = getZTools(); +if (zObj && typeof zObj.getPath === 'function') { + try { + store.init(zObj.getPath('userData')); + } catch (e) { + store.init(path.join(os.homedir(), '.ztools')); + } +} else { + store.init(path.join(os.homedir(), '.ztools')); +} + +// 彻底停用并清理插件内置的冗余鼠标监听,完全交由 ZTools 超级面板接管 +function checkAutoStartMouseHook() { + try { + stopMouseHook(); + } catch (e) {} +} + +// 启动鼠标中键监听 +function startMouseHook() { + const vault = store.load(); + const holdMs = (vault.config && vault.config.holdDurationMs) || 500; + + return mouseHook.start({ + holdDurationMs: holdMs, + onTrigger: () => { + if (typeof ztools !== 'undefined') { + try { + if (typeof ztools.showMainWindow === 'function') { + ztools.showMainWindow(); + } + if (typeof ztools.redirect === 'function') { + ztools.redirect('pwd-quick-fill', ''); + } + } catch (e) { + console.error('[preload] 触发快速选密界面异常:', e); + } + } + } + }); +} + +// 停止鼠标中键监听 +function stopMouseHook() { + mouseHook.stop(); + return true; +} + +// 校验密文对象结构 +function isValidCipherObj(obj) { + return ( + obj && + typeof obj === 'object' && + typeof obj.iv === 'string' && + typeof obj.tag === 'string' && + typeof obj.data === 'string' + ); +} + +// 密码管理器核心 API +const pwdApi = { + /** + * 仅测试/工具用途:外部刷新存储路径 + */ + initStorePath(userDataPath) { + store.init(userDataPath); + }, + + /** + * 刷新最近活动时间(用于空闲自动锁定计时) + */ + touchActivity() { + lastActivityAt = Date.now(); + }, + + /** + * 判断是否首次运行(未设置主密码) + */ + isFirstRun() { + const vault = store.load(); + return !vault.salt || !vault.verifyToken; + }, + + /** + * 首次设置主密码 PIN + * @param {string} pin + */ + setupMasterPin(pin) { + if (!pin || pin.length < 4) { + throw new Error('主密码长度不能少于 4 位'); + } + const salt = cryptoLib.generateSalt(); + const masterKey = cryptoLib.deriveMasterKey(pin, salt); + // 加密一个固定的校验串,用于后续校验解锁 PIN 是否正确 + const verifyToken = cryptoLib.encrypt(masterKey, 'VALID_MASTER_TOKEN'); + + const vault = store.load(); + vault.salt = salt; + vault.verifyToken = verifyToken; + vault.autoUnlockKey = null; + vault.config = Object.assign(vault.config || {}, { requireMasterPin: true }); + store.save(vault); + + cachedMasterKey = masterKey; + lastActivityAt = Date.now(); + pwdApi.broadcastMessage('sync-auth', { masterKeyHex: masterKey.toString('hex') }); + pwdApi.broadcastMessage('config-updated'); + return true; + }, + + /** + * 首次免密初始化(生成一个随机设备密钥以保持密码库仍为 AES-256-GCM 加密) + */ + setupWithoutMasterPin() { + const vault = store.load(); + if (vault.salt && vault.verifyToken) { + throw new Error('保险库已初始化,请在设置中管理主密码开关'); + } + + const salt = cryptoLib.generateSalt(); + const autoKey = crypto.randomBytes(32); + const verifyToken = cryptoLib.encrypt(autoKey, 'VALID_MASTER_TOKEN'); + + vault.salt = salt; + vault.verifyToken = verifyToken; + vault.autoUnlockKey = autoKey.toString('hex'); + vault.config = Object.assign(vault.config || {}, { requireMasterPin: false }); + store.save(vault); + + cachedMasterKey = autoKey; + lastActivityAt = Date.now(); + pwdApi.broadcastMessage('sync-auth', { masterKeyHex: autoKey.toString('hex') }); + pwdApi.broadcastMessage('config-updated'); + return true; + }, + + /** + * 解锁主密码 + * @param {string} pin + */ + unlock(pin) { + const vault = store.load(); + if (!vault.salt || !vault.verifyToken) { + throw new Error('尚未设置主密码,请先完成初始设置'); + } + try { + const masterKey = cryptoLib.deriveMasterKey(pin, vault.salt); + const plain = cryptoLib.decrypt(masterKey, vault.verifyToken); + if (plain === 'VALID_MASTER_TOKEN') { + cachedMasterKey = masterKey; + lastActivityAt = Date.now(); + pwdApi.broadcastMessage('sync-auth', { masterKeyHex: masterKey.toString('hex') }); + return true; + } + } catch (e) { + // 解密失败说明 PIN 错误 + } + return false; + }, + + /** + * 修改主密码(验证原密码并使用新盐值重新加密全部密码条目) + * @param {string} oldPin + * @param {string} newPin + */ + changeMasterPin(oldPin, newPin) { + if (!newPin || newPin.length < 4) { + throw new Error('新主密码长度不能少于 4 位'); + } + const vault = store.load(); + if (vault?.config?.requireMasterPin === false) { + throw new Error('当前处于免密模式,请先开启主密码解锁保护'); + } + if (!vault.salt || !vault.verifyToken) { + throw new Error('尚未设置主密码'); + } + + let oldKey; + try { + oldKey = cryptoLib.deriveMasterKey(oldPin, vault.salt); + const plain = cryptoLib.decrypt(oldKey, vault.verifyToken); + if (plain !== 'VALID_MASTER_TOKEN') { + throw new Error('原主密码校验失败'); + } + } catch (e) { + throw new Error('原主密码不正确'); + } + + // 先全部解密,防止中途出错导致数据不一致 + const plainPasswords = vault.entries.map((item) => ({ + id: item.id, + plainPwd: cryptoLib.decrypt(oldKey, item.encryptedPwd) + })); + + const newSalt = cryptoLib.generateSalt(); + const newKey = cryptoLib.deriveMasterKey(newPin, newSalt); + const newVerifyToken = cryptoLib.encrypt(newKey, 'VALID_MASTER_TOKEN'); + + const pwdMap = new Map(plainPasswords.map((x) => [x.id, x.plainPwd])); + vault.salt = newSalt; + vault.verifyToken = newVerifyToken; + vault.autoUnlockKey = null; + vault.entries = vault.entries.map((item) => { + const plain = pwdMap.get(item.id); + return Object.assign({}, item, { + encryptedPwd: cryptoLib.encrypt(newKey, plain) + }); + }); + + store.save(vault); + cachedMasterKey = newKey; + lastActivityAt = Date.now(); + pwdApi.broadcastMessage('sync-auth', { masterKeyHex: newKey.toString('hex') }); + return true; + }, + + /** + * 关闭主密码解锁保护(必须已在内存解锁,使用全新随机设备密钥重新加密全库) + */ + disableMasterPin() { + if (!cachedMasterKey) { + throw new Error('保险库已锁定,请先解锁后再关闭主密码保护'); + } + const vault = store.load(); + if (vault?.config?.requireMasterPin === false && vault.autoUnlockKey) { + return true; + } + + // 先用当前内存主密钥解密所有条目,避免与原主密码产生任何耦合 + const plainPasswords = vault.entries.map((item) => ({ + id: item.id, + plainPwd: cryptoLib.decrypt(cachedMasterKey, item.encryptedPwd) + })); + + const newSalt = cryptoLib.generateSalt(); + const autoKey = crypto.randomBytes(32); + const newVerifyToken = cryptoLib.encrypt(autoKey, 'VALID_MASTER_TOKEN'); + const pwdMap = new Map(plainPasswords.map((x) => [x.id, x.plainPwd])); + + vault.salt = newSalt; + vault.verifyToken = newVerifyToken; + vault.autoUnlockKey = autoKey.toString('hex'); + vault.config = Object.assign(vault.config || {}, { requireMasterPin: false }); + vault.entries = vault.entries.map((item) => { + const plain = pwdMap.get(item.id); + return Object.assign({}, item, { + encryptedPwd: cryptoLib.encrypt(autoKey, plain) + }); + }); + + store.save(vault); + cachedMasterKey = autoKey; + lastActivityAt = Date.now(); + pwdApi.broadcastMessage('sync-auth', { masterKeyHex: autoKey.toString('hex') }); + pwdApi.broadcastMessage('config-updated'); + return true; + }, + + /** + * 重新开启主密码解锁保护(设置新主密码并重新加密全库,彻底清除自动密钥) + * @param {string} newPin + */ + enableMasterPin(newPin) { + if (!newPin || newPin.length < 4) { + throw new Error('新主密码长度不能少于 4 位'); + } + tryAutoUnlock(); + if (!cachedMasterKey) { + throw new Error('保险库未解锁,无法开启主密码保护'); + } + + const vault = store.load(); + const plainPasswords = vault.entries.map((item) => ({ + id: item.id, + plainPwd: cryptoLib.decrypt(cachedMasterKey, item.encryptedPwd) + })); + + const newSalt = cryptoLib.generateSalt(); + const newKey = cryptoLib.deriveMasterKey(newPin, newSalt); + const newVerifyToken = cryptoLib.encrypt(newKey, 'VALID_MASTER_TOKEN'); + const pwdMap = new Map(plainPasswords.map((x) => [x.id, x.plainPwd])); + + vault.salt = newSalt; + vault.verifyToken = newVerifyToken; + vault.autoUnlockKey = null; + vault.config = Object.assign(vault.config || {}, { requireMasterPin: true }); + vault.entries = vault.entries.map((item) => { + const plain = pwdMap.get(item.id); + return Object.assign({}, item, { + encryptedPwd: cryptoLib.encrypt(newKey, plain) + }); + }); + + store.save(vault); + cachedMasterKey = newKey; + lastActivityAt = Date.now(); + pwdApi.broadcastMessage('sync-auth', { masterKeyHex: newKey.toString('hex') }); + pwdApi.broadcastMessage('config-updated'); + return true; + }, + + /** + * 检查是否启用了主密码解锁保护 + */ + isMasterPinRequired() { + const vault = store.load(); + return vault?.config?.requireMasterPin !== false; + }, + + /** + * 锁定(清空内存主密钥;免密模式下不执行锁定) + */ + lock() { + if (!this.isMasterPinRequired()) { + return false; + } + cachedMasterKey = null; + pwdApi.broadcastMessage('sync-lock'); + return true; + }, + + /** + * 检查是否已解锁(免密模式下自动恢复内存密钥) + */ + isUnlocked() { + if (!cachedMasterKey) { + tryAutoUnlock(); + } + return !!cachedMasterKey; + }, + + getMasterKeyHex() { + return cachedMasterKey ? cachedMasterKey.toString('hex') : null; + }, + + setMasterKeyHex(hex) { + if (hex && typeof hex === 'string') { + try { + cachedMasterKey = Buffer.from(hex, 'hex'); + lastActivityAt = Date.now(); + return true; + } catch (e) {} + } + return false; + }, + + /** + * 获取脱敏密码列表(不返回加密数据),按置顶与最近使用排序 + */ + listEntries() { + const vault = store.load(); + return sortEntries(vault.entries.map(toSafeEntry)); + }, + + /** + * 获取单条条目元信息 + * @param {string} id + */ + getEntry(id) { + const vault = store.load(); + const item = vault.entries.find((e) => e.id === id); + if (!item) return null; + return toSafeEntry(item); + }, + + /** + * 添加密码条目 + * @param {string} label 标签/网站名称 + * @param {string} username 用户名/账号 + * @param {string} plainPwd 密码明文 + * @param {object} [extra] 可选扩展字段 { note, pinned } + */ + addEntry(label, username, plainPwd, extra = {}) { + if (!cachedMasterKey) { + tryAutoUnlock(); + } + if (!cachedMasterKey) { + throw new Error('保险库已锁定,请先解锁'); + } + if (!label || !plainPwd) { + throw new Error('名称与密码不能为空'); + } + + lastActivityAt = Date.now(); + const encryptedPwd = cryptoLib.encrypt(cachedMasterKey, plainPwd); + const vault = store.load(); + const now = Date.now(); + const newEntry = { + id: store.newId(), + label: label.trim(), + username: (username || '').trim(), + note: (extra && typeof extra.note === 'string' ? extra.note : '').trim(), + pinned: !!(extra && extra.pinned), + lastUsedAt: 0, + useCount: 0, + encryptedPwd, + createdAt: now, + updatedAt: now + }; + vault.entries.unshift(newEntry); + store.save(vault); + pwdApi.broadcastMessage('data-updated'); + return newEntry.id; + }, + + /** + * 获取指定条目的明文密码 + * @param {string} id + */ + getPlainPwd(id) { + if (!cachedMasterKey) { + tryAutoUnlock(); + } + if (!cachedMasterKey) { + throw new Error('保险库已锁定,请先解锁'); + } + lastActivityAt = Date.now(); + const vault = store.load(); + const item = vault.entries.find((e) => e.id === id); + if (!item) { + throw new Error('条目不存在'); + } + return cryptoLib.decrypt(cachedMasterKey, item.encryptedPwd); + }, + + /** + * 更新条目 + * @param {string} id + * @param {string} label + * @param {string} username + * @param {string} [plainPwd] 可选,为空时不修改原密码 + * @param {object} [extra] 可选扩展字段 { note, pinned } + */ + updateEntry(id, label, username, plainPwd, extra = {}) { + if (!cachedMasterKey) { + tryAutoUnlock(); + } + if (!cachedMasterKey) { + throw new Error('保险库已锁定,请先解锁'); + } + lastActivityAt = Date.now(); + const vault = store.load(); + const item = vault.entries.find((e) => e.id === id); + if (!item) { + throw new Error('条目不存在'); + } + item.label = label.trim(); + item.username = (username || '').trim(); + if (extra && extra.note !== undefined) { + item.note = String(extra.note || '').trim(); + } + if (extra && extra.pinned !== undefined) { + item.pinned = !!extra.pinned; + } + if (plainPwd && plainPwd.length > 0) { + item.encryptedPwd = cryptoLib.encrypt(cachedMasterKey, plainPwd); + } + item.updatedAt = Date.now(); + store.save(vault); + pwdApi.broadcastMessage('data-updated'); + return true; + }, + + /** + * 切换置顶状态 + * @param {string} id + */ + togglePin(id) { + lastActivityAt = Date.now(); + const vault = store.load(); + const item = vault.entries.find((e) => e.id === id); + if (!item) { + throw new Error('条目不存在'); + } + item.pinned = !item.pinned; + store.save(vault); + pwdApi.broadcastMessage('data-updated'); + return item.pinned; + }, + + /** + * 记录条目最近使用时间与使用次数 + * @param {string} id + */ + recordUsage(id) { + if (!id) return false; + try { + const vault = store.load(); + const item = vault.entries.find((e) => e.id === id); + if (!item) return false; + item.lastUsedAt = Date.now(); + item.useCount = (item.useCount || 0) + 1; + store.save(vault); + pwdApi.broadcastMessage('data-updated'); + return true; + } catch (e) { + return false; + } + }, + + /** + * 删除条目 + * @param {string} id + */ + deleteEntry(id) { + lastActivityAt = Date.now(); + const vault = store.load(); + const index = vault.entries.findIndex((e) => e.id === id); + if (index === -1) { + throw new Error('条目不存在'); + } + vault.entries.splice(index, 1); + store.save(vault); + pwdApi.broadcastMessage('data-updated'); + return true; + }, + + /** + * 导出加密备份 JSON 字符串(免密模式包含 autoUnlockKey;主密码模式严禁包含 autoUnlockKey) + */ + exportVaultJson() { + const vault = store.load(); + const isPinDisabled = vault?.config?.requireMasterPin === false && !!vault.autoUnlockKey; + const payload = { + version: vault.version || 1, + exportedAt: new Date().toISOString(), + requireMasterPin: !isPinDisabled, + salt: vault.salt, + verifyToken: vault.verifyToken, + entries: vault.entries + }; + if (isPinDisabled) { + payload.autoUnlockKey = vault.autoUnlockKey; + } + return JSON.stringify(payload, null, 2); + }, + + /** + * 导入加密备份 JSON 字符串 + * @param {string} jsonStr + * @returns {{ unlocked: boolean, count: number, requireMasterPin: boolean }} + */ + importVaultJson(jsonStr) { + let parsed; + try { + parsed = JSON.parse(jsonStr); + } catch (e) { + throw new Error('备份文件不是有效的 JSON 格式'); + } + if (!parsed || typeof parsed !== 'object') { + throw new Error('备份文件格式错误'); + } + if (!parsed.salt || typeof parsed.salt !== 'string') { + throw new Error('备份缺少有效的加密盐值 (salt)'); + } + if (!isValidCipherObj(parsed.verifyToken)) { + throw new Error('备份缺少有效的校验令牌 (verifyToken)'); + } + if (!Array.isArray(parsed.entries)) { + throw new Error('备份缺少条目列表 (entries)'); + } + for (let i = 0; i < parsed.entries.length; i++) { + const entry = parsed.entries[i]; + if (!entry || !entry.id || !entry.label || !isValidCipherObj(entry.encryptedPwd)) { + throw new Error(`备份第 ${i + 1} 条记录结构不完整`); + } + } + + const currentVault = store.load(); + const isPinDisabledBackup = + parsed.requireMasterPin === false && + typeof parsed.autoUnlockKey === 'string' && + /^[0-9a-fA-F]{64}$/.test(parsed.autoUnlockKey); + + if (isPinDisabledBackup) { + let autoKey = null; + let validAutoBackup = false; + try { + autoKey = Buffer.from(parsed.autoUnlockKey, 'hex'); + const plain = cryptoLib.decrypt(autoKey, parsed.verifyToken); + validAutoBackup = plain === 'VALID_MASTER_TOKEN'; + } catch (e) {} + + if (!validAutoBackup) { + throw new Error('免密备份校验失败,自动密钥与校验令牌不匹配'); + } + + const nextVault = { + version: parsed.version || 1, + salt: parsed.salt, + verifyToken: parsed.verifyToken, + autoUnlockKey: parsed.autoUnlockKey, + entries: parsed.entries, + config: Object.assign({}, currentVault.config, { requireMasterPin: false }) + }; + store.save(nextVault); + cachedMasterKey = autoKey; + lastActivityAt = Date.now(); + pwdApi.broadcastMessage('sync-auth', { masterKeyHex: autoKey.toString('hex') }); + pwdApi.broadcastMessage('data-updated'); + pwdApi.broadcastMessage('config-updated'); + + return { + unlocked: true, + count: nextVault.entries.length, + requireMasterPin: false + }; + } + + const nextVault = { + version: parsed.version || 1, + salt: parsed.salt, + verifyToken: parsed.verifyToken, + autoUnlockKey: null, + entries: parsed.entries, + config: Object.assign({}, currentVault.config, { requireMasterPin: true }) + }; + store.save(nextVault); + + let stillUnlocked = false; + if (cachedMasterKey) { + try { + const plain = cryptoLib.decrypt(cachedMasterKey, nextVault.verifyToken); + if (plain === 'VALID_MASTER_TOKEN') { + stillUnlocked = true; + } + } catch (e) {} + } + + if (stillUnlocked) { + lastActivityAt = Date.now(); + pwdApi.broadcastMessage('data-updated'); + } else { + cachedMasterKey = null; + pwdApi.broadcastMessage('sync-lock'); + } + pwdApi.broadcastMessage('config-updated'); + + return { + unlocked: stillUnlocked, + count: nextVault.entries.length, + requireMasterPin: true + }; + }, + + /** + * 安全复制敏感明文密码到剪贴板,并按配置计划自动清空 + * @param {string} plainText + */ + async copySecret(plainText) { + lastActivityAt = Date.now(); + const ok = await writeClipboardReliable(plainText); + if (ok) { + const config = this.getConfig(); + const seconds = config.autoClearClipboardSeconds || 10; + scheduleClipboardClear(plainText, seconds); + } + return ok; + }, + + /** + * 复制普通非敏感文本(如用户名),并取消旧敏感清理定时器防误清 + * @param {string} text + */ + async copyPlainText(text) { + lastActivityAt = Date.now(); + cancelClipboardClear(); + return writeClipboardReliable(text); + }, + + /** + * 获取配置 + */ + getConfig() { + const vault = store.load(); + return Object.assign({}, vault.config, { + mouseHookRunning: mouseHook.isRunning() + }); + }, + + /** + * 更新配置(不允许通过普通配置接口直接绕过加密流程篡改 requireMasterPin) + * @param {object} patch + */ + setConfig(patch) { + const vault = store.load(); + const safePatch = Object.assign({}, patch); + delete safePatch.requireMasterPin; + vault.config = Object.assign(vault.config || {}, safePatch); + store.save(vault); + + vault.config.middleClickTrigger = false; + stopMouseHook(); + return vault.config; + }, + + /** + * 获取当前运行平台 ('win32' | 'darwin' | 'linux') + */ + getPlatform() { + return process.platform; + }, + + /** + * 自动将密码安全填入目标前台窗口 + * @param {string} plainPwd 密码明文 + * @param {string} [mode='paste'] 'paste' | 'type' + * @param {boolean} [isDetachedMode=false] 是否处于独立窗口中 + */ + async autoFill(plainPwd, mode = 'paste', isDetachedMode = false) { + return this.autoFillCredentials({ + password: plainPwd, + mode, + fillBoth: false, + isDetachedMode + }); + }, + + /** + * 自动将账号与密码填入前台窗口对应输入框中(支持 账号 ➔ Tab ➔ 密码 双框严格保序联动) + * @param {object} options + * @param {string} [options.entryId] 条目 ID(用于填充后静默记录使用统计) + * @param {string} [options.username] 账号/用户名 + * @param {string} [options.password] 密码明文(仅填账号时可为空) + * @param {string} [options.mode='paste'] 'paste' | 'type' + * @param {boolean} [options.fillBoth=true] 是否自动联动填充账号与密码(fillTarget 未指定时生效) + * @param {string} [options.fillTarget] 填充目标:'both' | 'username' | 'password' + * @param {boolean} [options.isDetachedMode=false] 是否处于独立窗口中 + * @param {number} [options.tabDelayMs] Tab 切换键后等待时长(未传入时读取配置) + */ + async autoFillCredentials({ entryId, username, password, mode = 'paste', fillBoth = true, fillTarget, isDetachedMode = false, tabDelayMs }) { + if (isAutoFilling) { + return false; + } + + const z = getZTools(); + const addon = getNativeAddon(); + const isMac = process.platform === 'darwin'; + + const cleanUsername = (username || '').trim(); + const plainPassword = password || ''; + + // 解析最终填充目标,兼容旧的 fillBoth 布尔参数 + let target = fillTarget; + if (!target) { + target = fillBoth && cleanUsername ? 'both' : 'password'; + } + if (target === 'both' && !cleanUsername) target = 'password'; + if (target === 'username' && !cleanUsername) return false; + if (target !== 'username' && !plainPassword) return false; + + const shouldFillBoth = target === 'both'; + + isAutoFilling = true; + lastActivityAt = Date.now(); + + try { + // 第一步立刻取消上一次剪贴板清理计划,杜绝旧定时器在本次填充中途误清空剪贴板 + cancelClipboardClear(); + + // 统一读取配置与默认值 + const defaultCfg = typeof store.getDefaultVault === 'function' ? store.getDefaultVault().config : { fillDelayMs: 450, tabDelayMs: 180, autoClearClipboardSeconds: 10 }; + let fillDelayMs = defaultCfg.fillDelayMs || 450; + let resolvedTabDelayMs = parseInt(tabDelayMs, 10) || defaultCfg.tabDelayMs || 180; + let clearSeconds = defaultCfg.autoClearClipboardSeconds || 10; + + try { + const vault = store.load(); + const cfg = vault?.config || {}; + if (cfg.fillDelayMs) { + fillDelayMs = parseInt(cfg.fillDelayMs, 10) || fillDelayMs; + } + if (!tabDelayMs && cfg.tabDelayMs) { + resolvedTabDelayMs = parseInt(cfg.tabDelayMs, 10) || resolvedTabDelayMs; + } + if (cfg.autoClearClipboardSeconds) { + clearSeconds = parseInt(cfg.autoClearClipboardSeconds, 10) || clearSeconds; + } + } catch (e) {} + + // 1. 隐藏窗口让出前台焦点给目标应用 + if (isDetachedMode) { + pwdApi.minimizeSelf(); + } else if (z && typeof z.hideMainWindow === 'function') { + try { await z.hideMainWindow(true); } catch (e) {} + } + + await sleep(fillDelayMs); + + let usedClipboardForPassword = false; + + // 单个字段填充工具(确保严格串行且剪贴板落盘后再粘贴) + const fillSingleValue = async (val, isSecretField) => { + if (!val) return; + if (mode === 'type' && addon && typeof addon.unicodeType === 'function') { + try { + const segments = [...new Intl.Segmenter().segment(val)]; + for (const seg of segments) { + if (seg.segment === '\n') { + if (addon.simulateKeyboardTap) addon.simulateKeyboardTap('enter', 'shift'); + } else { + addon.unicodeType(seg.segment); + } + await sleep(8); + } + return; + } catch (e) {} + } + + // 可靠单通道写剪贴板 + 回读验证 + 等待系统剪贴板通知释放后再粘贴 + await writeClipboardReliable(val); + await sleep(45); + if (isSecretField) { + usedClipboardForPassword = true; + } + + if (addon && typeof addon.simulatePaste === 'function') { + try { + addon.simulatePaste(); + } catch (e) {} + } else if (z && typeof z.simulateKeyboardTap === 'function') { + try { + const mod = isMac ? 'command' : 'control'; + z.simulateKeyboardTap('v', mod); + } catch (e) {} + } + }; + + // 2. 执行填充流程(严格串行保序) + if (shouldFillBoth) { + // 2.1 填入用户名(不计为敏感清理) + await fillSingleValue(cleanUsername, false); + + // 2.2 充分等待目标窗口(尤其是浏览器网页)彻底消费完第一个粘贴事件,再发送 Tab 切换焦点 + await sleep(mode === 'type' ? 120 : 200); + + if (addon && typeof addon.simulateKeyboardTap === 'function') { + try { + addon.simulateKeyboardTap('tab'); + } catch (e) {} + } else if (z && typeof z.simulateKeyboardTap === 'function') { + try { + z.simulateKeyboardTap('tab'); + } catch (e) {} + } + + // 2.3 等待输入框焦点切换与网页事件完成 + await sleep(resolvedTabDelayMs); + + // 2.4 写入并填入密码 + await fillSingleValue(plainPassword, true); + } else if (target === 'username') { + await fillSingleValue(cleanUsername, false); + } else { + await fillSingleValue(plainPassword, true); + } + + // 3. 记录条目使用统计 + if (entryId) { + this.recordUsage(entryId); + } + + // 4. 仅当密码确实通过剪贴板粘贴时,安排智能清空剪贴板 + if (target !== 'username' && usedClipboardForPassword) { + scheduleClipboardClear(plainPassword, clearSeconds); + } + + return true; + } finally { + isAutoFilling = false; + } + }, + + bringToFront() { + if (typeof window !== 'undefined') { + try { + window.focus(); + } catch (e) {} + } + const addon = getNativeAddon(); + if (addon && typeof addon.activateWindow === 'function') { + try { + if (typeof process !== 'undefined') { + // 优先激活父进程(Electron 主进程 PID,负责持有原生 HWND) + if (process.ppid) addon.activateWindow(process.ppid); + if (process.pid) addon.activateWindow(process.pid); + } + } catch (e) {} + } + }, + + minimizeSelf() { + // 1. 如果当前主进程持有该独立子窗口引用,直接原生调用 minimize() 瞬间最小化 + if (standaloneWindow && !standaloneWindow.isDestroyed()) { + try { + if (typeof standaloneWindow.minimize === 'function') { + standaloneWindow.minimize(); + return true; + } + } catch (e) {} + } + // 2. 如果自己是子窗口,向父进程发送极速最小化通知 + const z = getZTools(); + if (z && typeof z.sendToParent === 'function') { + try { + z.sendToParent('minimize-standalone-window'); + } catch (e) {} + } + // 3. 页面级释放焦点兜底 + if (typeof window !== 'undefined' && typeof window.blur === 'function') { + try { + window.blur(); + } catch (e) {} + } + return false; + }, + + startMouseHook, + stopMouseHook, + + /** + * 打开或唤起独立的密码管理器窗口 (BrowserWindow) + * @param {object} [action] 可选启动参数(携带 payload) + */ + openManagerWindow(action) { + const z = getZTools(); + if (!z || typeof z.createBrowserWindow !== 'function') { + console.warn('[pwdApi] ztools.createBrowserWindow 不可用'); + return false; + } + + // 1. 若窗口已存在且未销毁,直接恢复展示、聚焦置顶 + if (standaloneWindow && !standaloneWindow.isDestroyed()) { + try { + if (typeof standaloneWindow.isMinimized === 'function' && standaloneWindow.isMinimized()) { + standaloneWindow.restore(); + } + if (typeof standaloneWindow.setAlwaysOnTop === 'function') { + standaloneWindow.setAlwaysOnTop(true); + } + standaloneWindow.show(); + standaloneWindow.focus(); + if (typeof standaloneWindow.setAlwaysOnTop === 'function') { + standaloneWindow.setAlwaysOnTop(false); + } + if (action) { + try { + standaloneWindow.webContents.send('plugin-action', action); + } catch (e) {} + } + if (cachedMasterKey) { + try { + standaloneWindow.webContents.send('sync-auth', { + masterKeyHex: cachedMasterKey.toString('hex') + }); + } catch (e) {} + } + return true; + } catch (e) { + console.error('[pwdApi] 唤起已有窗口失败:', e); + } + } + + // 2. 窗口未创建或已关闭,初始化独立窗口配置 + const isDark = typeof z.isDarkColors === 'function' && z.isDarkColors(); + const winOptions = { + title: '快速密码填充 - 密码管理器', + width: 880, + height: 620, + minWidth: 640, + minHeight: 450, + center: true, + resizable: true, + maximizable: true, + minimizable: true, + frame: true, + autoHideMenuBar: true, + backgroundColor: isDark ? '#1e293b' : '#ffffff', + webPreferences: { + preload: 'preload.js' + } + }; + + try { + const iconPath = path.join(__dirname, 'logo.png'); + if (fs.existsSync(iconPath)) { + winOptions.icon = iconPath; + } + } catch (e) {} + + try { + standaloneWindow = z.createBrowserWindow('index.html', winOptions, () => { + if (standaloneWindow && !standaloneWindow.isDestroyed()) { + try { + if (action) { + standaloneWindow.webContents.send('plugin-action', action); + } + if (cachedMasterKey) { + standaloneWindow.webContents.send('sync-auth', { + masterKeyHex: cachedMasterKey.toString('hex') + }); + } + } catch (e) {} + } + }); + return true; + } catch (err) { + console.error('[pwdApi] 创建独立窗口异常:', err); + return false; + } + }, + + activateStandaloneWindow(action) { + if (standaloneWindow && !standaloneWindow.isDestroyed()) { + try { + if (typeof standaloneWindow.isMinimized === 'function' && standaloneWindow.isMinimized()) { + standaloneWindow.restore(); + } + if (typeof standaloneWindow.setAlwaysOnTop === 'function') { + standaloneWindow.setAlwaysOnTop(true); + } + standaloneWindow.show(); + standaloneWindow.focus(); + if (typeof standaloneWindow.setAlwaysOnTop === 'function') { + standaloneWindow.setAlwaysOnTop(false); + } + if (action) { + try { standaloneWindow.webContents.send('plugin-action', action); } catch (e) {} + } + return true; + } catch (e) {} + } + return false; + }, + + getStandaloneWindow() { + return (standaloneWindow && !standaloneWindow.isDestroyed()) ? standaloneWindow : null; + }, + + /** + * 监听来自其他窗口的消息(基于 electron.ipcRenderer) + */ + onWindowMessage(channel, callback) { + if (electron && electron.ipcRenderer) { + const handler = (_event, ...args) => callback(...args); + electron.ipcRenderer.on(channel, handler); + return () => { + try { + electron.ipcRenderer.removeListener(channel, handler); + } catch (e) {} + }; + } + return () => {}; + }, + + /** + * 跨窗口消息广播(同时向子窗口与父窗口发送) + */ + broadcastMessage(channel, ...args) { + // 1. 向子窗口发送 + if (standaloneWindow && !standaloneWindow.isDestroyed()) { + try { + standaloneWindow.webContents.send(channel, ...args); + } catch (e) {} + } + // 2. 向父窗口发送 (如果自己是子窗口) + const z = getZTools(); + if (z && typeof z.sendToParent === 'function') { + try { + z.sendToParent(channel, ...args); + } catch (e) {} + } + } +}; + +// 监听 IPC 同步消息 +if (electron && electron.ipcRenderer) { + electron.ipcRenderer.on('sync-auth', (_event, data) => { + if (data && data.masterKeyHex) { + try { + cachedMasterKey = Buffer.from(data.masterKeyHex, 'hex'); + lastActivityAt = Date.now(); + } catch (e) {} + } + }); + + electron.ipcRenderer.on('sync-lock', () => { + cachedMasterKey = null; + }); + + electron.ipcRenderer.on('minimize-standalone-window', () => { + if (standaloneWindow && !standaloneWindow.isDestroyed()) { + try { + standaloneWindow.minimize(); + } catch (e) {} + } + }); +} + +// 挂载到 window 对象供渲染层直接使用 +if (typeof window !== 'undefined') { + window.pwdApi = pwdApi; +} + +// 导出 API 供测试脚本直接引用(不影响 Electron preload 行为) +if (typeof module !== 'undefined' && module.exports) { + module.exports = { pwdApi }; +} + +// 监听 ZTools 插件生命周期退出事件 +if (typeof ztools !== 'undefined' && typeof ztools.onPluginOut === 'function') { + ztools.onPluginOut(() => { + // 退出时清理自动锁定检查及后台监听 + if (autoLockCheckInterval) { + clearInterval(autoLockCheckInterval); + autoLockCheckInterval = null; + } + if (clearClipboardTimer && lastSensitiveClipboard) { + const pendingSecret = lastSensitiveClipboard; + cancelClipboardClear(); + performSmartClipboardClear(pendingSecret).catch(() => {}); + } + mouseHook.stop(); + cachedMasterKey = null; + }); +} + +// 初始化时清理冗余鼠标监听、检查免密自动恢复并启动空闲锁定检查 +checkAutoStartMouseHook(); +tryAutoUnlock(); +ensureAutoLockMonitor(); diff --git a/plugins/ztools-quick-pwd/scripts/mid-btn-watch.ps1 b/plugins/ztools-quick-pwd/scripts/mid-btn-watch.ps1 new file mode 100644 index 000000000..eee51e6ad --- /dev/null +++ b/plugins/ztools-quick-pwd/scripts/mid-btn-watch.ps1 @@ -0,0 +1,52 @@ +param ( + [int]$HoldDurationMs = 500 +) + +$OutputEncoding = [Console]::OutputEncoding = [System.Text.Encoding]::UTF8 + +Add-Type -TypeDefinition @" +using System; +using System.Runtime.InteropServices; +public class MouseHookNative { + [DllImport("user32.dll")] + public static extern short GetAsyncKeyState(int vKey); + [StructLayout(LayoutKind.Sequential)] + public struct POINT { public int X; public int Y; } + [DllImport("user32.dll")] + public static extern bool GetCursorPos(out POINT lpPoint); +} +"@ + +$VK_MBUTTON = 0x04 +$pressing = $false +$pressStartTime = 0 + +while ($true) { + Start-Sleep -Milliseconds 25 + $state = [MouseHookNative]::GetAsyncKeyState($VK_MBUTTON) + $isDown = ($state -band 0x8000) -ne 0 + if ($isDown) { + $now = [Environment]::TickCount + if (-not $pressing) { + $pressing = $true + $pressStartTime = $now + } else { + $elapsed = $now - $pressStartTime + if ($elapsed -lt 0) { $elapsed = $elapsed + [int]::MaxValue } + if ($elapsed -ge $HoldDurationMs) { + $point = New-Object MouseHookNative+POINT + [MouseHookNative]::GetCursorPos([ref]$point) | Out-Null + Write-Output "TRIGGER $($point.X),$($point.Y)" + [Console]::Out.Flush() + while ($true) { + Start-Sleep -Milliseconds 40 + $curState = [MouseHookNative]::GetAsyncKeyState($VK_MBUTTON) + if (($curState -band 0x8000) -eq 0) { break } + } + $pressing = $false + } + } + } else { + $pressing = $false + } +} diff --git a/plugins/ztools-quick-pwd/scripts/pack.js b/plugins/ztools-quick-pwd/scripts/pack.js new file mode 100644 index 000000000..1f80cd2c6 --- /dev/null +++ b/plugins/ztools-quick-pwd/scripts/pack.js @@ -0,0 +1,110 @@ +/** + * 打包插件为 .zpx(ZTools 官方格式: gzip(asar archive)) + * 用法: node scripts/pack.js + * 产物: 项目根目录 ztools-quick-pwd-.zpx + */ +const { createGzip } = require("zlib"); +const { createReadStream, createWriteStream, existsSync, readFileSync, mkdirSync, copyFileSync, rmSync, statSync } = require("fs"); +const os = require("os"); +const path = require("path"); +const { pipeline } = require("stream/promises"); + +// 优先引用本地或同级项目的 @electron/asar +let asar; +try { + asar = require("@electron/asar"); +} catch { + try { + const { createRequire } = require("module"); + const req = createRequire(path.join(__dirname, "../../ztools-mise-manager/package.json")); + asar = req("@electron/asar"); + } catch (err) { + console.error("❌ 未找到 @electron/asar 模块,请先运行: npm i -D @electron/asar"); + process.exit(1); + } +} + +async function main() { + const root = path.join(__dirname, ".."); + const pluginJsonPath = path.join(root, "plugin.json"); + + if (!existsSync(pluginJsonPath)) { + console.error("❌ 未找到 plugin.json"); + process.exit(1); + } + + const meta = JSON.parse(readFileSync(pluginJsonPath, "utf-8")); + const version = meta.version || "0.0.1"; + const name = meta.name || "ztools-quick-pwd"; + const outPath = path.join(root, `${name}-${version}.zpx`); + const outZipPath = path.join(root, `${name}-${version}.zip`); + + // 创建干净的临时暂存目录 + const stageDir = path.join(os.tmpdir(), `${name}-stage-${Date.now()}`); + mkdirSync(stageDir, { recursive: true }); + + const filesToCopy = [ + "plugin.json", + "preload.js", + "index.html", + "index.css", + "index.js", + "logo.png", + "README.md", + "CHANGELOG.md", + "MANUAL.md", + "libs/crypto.js", + "libs/mouse-hook.js", + "libs/store.js", + ]; + + for (const rel of filesToCopy) { + const srcFile = path.join(root, rel); + const dstFile = path.join(stageDir, rel); + if (existsSync(srcFile)) { + mkdirSync(path.dirname(dstFile), { recursive: true }); + copyFileSync(srcFile, dstFile); + } + } + + // 临时 asar 文件 + const tempAsar = path.join(os.tmpdir(), `pack-${Date.now()}-${Math.random().toString(36).slice(2, 8)}.asar`); + const prevNoAsar = process.noAsar; + process.noAsar = true; + + try { + console.log("[ZPX] 开始打包..."); + // 目录 → asar 归档 + await asar.createPackage(stageDir, tempAsar); + // asar → gzip → .zpx + await pipeline(createReadStream(tempAsar), createGzip(), createWriteStream(outPath)); + const size = statSync(outPath).size; + console.log(`[ZPX] 打包完成: ${outPath} (${(size / 1024).toFixed(1)} KB)`); + + // 同时生成通用 .zip 包 + try { + const { execSync } = require("child_process"); + if (process.platform === "win32") { + execSync(`powershell.exe -NoProfile -Command "Compress-Archive -Path '${stageDir}\\*' -DestinationPath '${outZipPath}' -Force"`); + } else { + // macOS / Linux 标准 zip 归档 + execSync(`cd "${stageDir}" && zip -r -q "${outZipPath}" .`); + } + const zipSize = statSync(outZipPath).size; + console.log(`[ZIP] 打包完成: ${outZipPath} (${(zipSize / 1024).toFixed(1)} KB)`); + } catch (zipErr) { + console.warn("⚠️ 生成 .zip 失败 (不影响 .zpx):", zipErr.message); + } + } finally { + try { + rmSync(tempAsar, { force: true }); + rmSync(stageDir, { recursive: true, force: true }); + } catch {} + process.noAsar = prevNoAsar; + } +} + +main().catch((e) => { + console.error("❌ 打包失败:", e); + process.exit(1); +});