From 05b881d79ec44da64f365be5c0e277dd06ed5e6d Mon Sep 17 00:00:00 2001 From: Wxw-Gu <84499436+Wxw-Gu@users.noreply.github.com> Date: Fri, 6 Nov 2026 11:10:01 +0800 Subject: [PATCH] =?UTF-8?q?fix:=20mac=20arm=E9=80=9A=E8=BF=87=E6=96=87?= =?UTF-8?q?=E4=BB=B6=E5=A4=B9=E6=89=93=E5=BC=80=E8=A2=AB=E5=88=A4=E5=AE=9A?= =?UTF-8?q?=E4=B8=BAintel=E8=8A=AF=E7=89=87=20mac=20os=E5=8D=87=E7=BA=A727?= =?UTF-8?q?=20=E6=9D=83=E9=99=90=E9=97=AE=E9=A2=98=E8=A7=A3=E5=86=B3?= =?UTF-8?q?=E6=96=87=E6=A1=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/README.md | 1 + docs/platform/macos.md | 32 ++- .../user-guide/macos27-permission-recovery.md | 247 ++++++++++++++++++ docs/user-guide/troubleshooting.md | 12 +- scripts/after-pack.cjs | 29 ++ src/main/index.ts | 11 +- src/main/key-service-mac.ts | 36 ++- src/main/macos-arch.ts | 60 +++++ src/main/services/ai-provider-service.ts | 38 ++- .../src/components/DatabaseConnectionPage.tsx | 30 ++- .../database-key/DatabaseKeyAutoDetect.tsx | 44 +++- src/renderer/src/styles/chat.scss | 30 +++ src/shared/connection-diagnostics.ts | 7 + src/shared/database-key.ts | 17 ++ src/shared/macos-arch.ts | 80 ++++++ .../database-key-arch-mismatch.test.tsx | 92 +++++++ tests/unit/after-pack-electron-arch.test.ts | 82 ++++++ tests/unit/macos-arch.test.ts | 247 ++++++++++++++++++ 18 files changed, 1066 insertions(+), 29 deletions(-) create mode 100644 docs/user-guide/macos27-permission-recovery.md create mode 100644 src/main/macos-arch.ts create mode 100644 src/shared/macos-arch.ts create mode 100644 tests/component/database-key-arch-mismatch.test.tsx create mode 100644 tests/unit/after-pack-electron-arch.test.ts create mode 100644 tests/unit/macos-arch.test.ts diff --git a/docs/README.md b/docs/README.md index 5493ace..18ca6f2 100644 --- a/docs/README.md +++ b/docs/README.md @@ -45,6 +45,7 @@ Agent Hub 让微信机器人调用本机 TraceMemo;Reader Skill / Local HTTP A - [导出聊天](./user-guide/export.md):导出 HTML、Markdown、CSV 或 JSON 档案。 - [数据、隐私与安全](./user-guide/privacy.md):本地处理、Provider、媒体和 Token 的数据边界。 - [常见问题与排查](./user-guide/troubleshooting.md):按安装、连接、AI、媒体和 Agent 现象排查。 +- [macOS 更新27后读不到微信数据](./user-guide/macos27-permission-recovery.md):升级 macOS 或更新应用后失去微信数据访问权限的恢复步骤。 ## 开发文档 diff --git a/docs/platform/macos.md b/docs/platform/macos.md index 072ef67..18da1d3 100644 --- a/docs/platform/macos.md +++ b/docs/platform/macos.md @@ -19,7 +19,12 @@ TraceMemo 需要读取微信本地数据。macOS 会根据系统版本、微信 如果你在连接页看到「最近验证结果:无法读取微信数据库」(错误码 `DATABASE_PERMISSION_DENIED`),并且已经确认微信数据目录**实际存在**(例如在终端里能列出 `db_storage/session/session.db`),那说明是 **TraceMemo 这个进程**读不到,而不是文件缺失。 -macOS 27 及更高版本对其他应用的容器数据有更严格的访问控制。给 TraceMemo 授予「完全磁盘访问权限」: +微信数据放在另一个应用的沙盒容器里,macOS 会对这种跨应用访问单独做校验。先看「完全磁盘访问权限」里 TraceMemo 的状态,再按情况处理: + +- **不在列表里,或开关是关的**:按下面的步骤授权。 +- **开关已经是开的,但仍然读不到**:这不是「没授权」,而是旧授权记录对不上当前版本的应用,需要先清掉旧记录再重新授权。完整步骤见[macOS 更新后读不到微信数据:权限恢复](../user-guide/macos27-permission-recovery.md)。 + +首次授权的步骤: 1. 打开 **系统设置 → 隐私与安全性 → 完全磁盘访问权限** 2. 找到 **TraceMemo**,打开开关 @@ -61,6 +66,29 @@ TraceMemo 同时支持两种 Mac 架构: - Apple Silicon:`tracememo-<版本号>-arm64.dmg` - Intel:`tracememo-<版本号>-x64.dmg` -两种架构都可以通过应用内的连接流程自动获取微信数据库密钥。首次连接时,TraceMemo 会根据当前机器架构进入对应的流程,按连接页面提示操作即可。 +两种架构都可以通过应用内的连接流程自动获取微信数据库密钥。首次连接时,TraceMemo 会按**当前运行的这个版本**进入对应流程,按连接页面提示操作即可。 + +### 提示「Intel Mac 自动获取」,但电脑是 Apple 芯片 + +如果在 M 系列 Mac 上看到「Intel Mac 自动获取」,或页面要求准备 Intel 连接环境,多数是**正在运行 Intel(x64)版 TraceMemo**。macOS 允许 Intel 版应用在 Apple 芯片上通过 Rosetta 运行,应用本身不会报错,但会如实把自己识别成 Intel 版本,于是走了 Intel 的密钥获取方式。 + +判断当前跑的是哪个版本: + +- 打开「活动监视器」,选中 TraceMemo,看「种类」一列 —— 显示「Apple」是 arm64 版,显示「Intel」是 x64 版; +- 或点连接页的「复制脱敏诊断摘要」,看「处理器架构」和「硬件架构」两行。 + +**启动方式不会改变架构。** Finder、Dock、桌面文件夹、`open` 命令打开的都是同一个 `.app`。但如果电脑上存在多个 TraceMemo 副本(例如「应用程序」里一个、下载文件夹里一个),不同入口可能打开不同副本,表现出来就像「有时是 Intel、有时不是」。列出所有副本及架构: + +```bash +mdfind "kMDItemCFBundleIdentifier == 'com.tracememo.app'" | while read -r p; do + [ -f "$p/Contents/MacOS/TraceMemo" ] && printf '%s -> ' "$p" && file -b "$p/Contents/MacOS/TraceMemo" +done +``` + +输出里带 `arm64` 的是 Apple 芯片版,带 `x86_64` 的是 Intel 版。 + +解决办法是从 [Releases](https://github.com/Wxw-Gu/TraceMemo/releases) 下载文件名带 `arm64` 的包,替换现有应用后重启。已保存的数据库密钥和连接配置不需要重新设置。 + +这与[提示「无法读取微信数据库」](#提示无法读取微信数据库时)不是同一个问题:那边是系统授权失效,这里是装错了版本。两种情况的处理方式不同,都不需要关闭 SIP。 Apple Silicon 和 Intel 已适配微信 macOS `4.1.13`。不同架构、微信版本和系统授权状态可能导致连接结果不同;文档不对所有组合做兼容性保证。 diff --git a/docs/user-guide/macos27-permission-recovery.md b/docs/user-guide/macos27-permission-recovery.md new file mode 100644 index 0000000..79773c2 --- /dev/null +++ b/docs/user-guide/macos27-permission-recovery.md @@ -0,0 +1,247 @@ +# macOS 更新后读不到微信数据:权限恢复 + +本文只处理一种情况:**TraceMemo 之前能连上微信数据库,升级 macOS 或更新 TraceMemo 之后读不到了**。 + +正常使用、没有出现权限提示的用户,不需要做任何操作。 + +--- + +## 1. 适用版本与典型表现 + +### 适用系统 + +- macOS 27 及更高版本(本文的主要场景) +- 从 macOS 26 或更早版本升级到 macOS 27 之后首次启动 TraceMemo +- TraceMemo 2.5.2 及更高版本(更早的版本升到新版时同样可能出现),且此前已经成功连接过一次微信数据库 + +如果你从来没有成功连接过,卡在「自动获取密钥」这一步,那不是本文的场景,请看[第一次使用](./getting-started.md)里的密钥获取流程。 + +### 典型表现 + +出现下面任意一条,且**微信数据目录确实存在**,再按本文处理: + +- 连接页提示「无法读取微信数据库」,错误码 `DATABASE_PERMISSION_DENIED` +- 提示「无法打开数据库」,但微信能正常登录、聊天记录能正常查看(权限不足有时会被包装成「打不开」) +- 昨天还能用,更新应用后重启就连接失败,期间没有换账号、没有迁移数据目录 +- 「系统设置 → 隐私与安全性 → 完全磁盘访问权限」里,TraceMemo 的开关是**打开**的,但应用仍然读不到 + +如果提示的是「**密钥与当前账号不匹配**」,那不属于本文范围 —— 那是密钥和账号对不上,按[常见问题与排查](./troubleshooting.md#连接微信失败)里的密钥流程处理。 + +判断数据目录是否真的存在,可以在终端执行(把路径里的账号目录换成你自己的): + +```bash +ls ~/Library/Containers/com.tencent.xinWeChat/Data/Documents/xwechat_files +``` + +能列出账号目录,说明数据是完整的,问题出在**权限**,不在文件。 + +> 终端能读到、TraceMemo 读不到,是完全正常的情况。macOS 的隐私权限按「应用」判定,不按「用户」判定,两者走的是两套不同的检查。所以「终端能读」不能用来排除权限问题。 + +--- + +## 2. 为什么更新应用之后会失去访问权限 + +一句话:**macOS 认的是应用文件的「指纹」,不是应用的名字。** + +TraceMemo 目前发布的 macOS 版本没有使用 Apple 开发者证书签名,用的是 ad-hoc 签名(相当于临时签名,没有可核验的开发者身份)。这种签名没有稳定的身份标识,系统只能靠应用二进制的指纹来记住「这是哪个应用、你给它授过什么权」。 + +每次发布新版本,二进制内容通常会变,指纹随之改变。系统看到的是一个指纹不同的新应用,之前那条授权记录对不上号,于是按「未授权」处理 —— 微信数据在另一个应用的沙盒容器里,读取被拒绝,连接页就报「无法读取微信数据库」。 + +几个容易误解的点: + +- **不是数据库损坏**。数据一直好好的,微信自己也能正常读写。 +- **不是密钥失效**。密钥还在本地,验证也没问题,卡住的是「打开文件」这一步。 +- **不是 macOS 27 单独引入的缺陷**。指纹变化导致授权失效,在更早的 macOS 上也会发生;macOS 27 上反馈更集中,但没有做过版本对照验证。 +- **重装应用通常无效**。重装会生成同样的新指纹,旧授权依旧对不上。 + +--- + +## 3. 一次性终端修复 + +先**完全退出** TraceMemo,不是关窗口,是退出进程: + +- 菜单栏 `TraceMemo → 退出 TraceMemo`,或按 `Command + Q` +- 托盘/菜单栏图标里如果有「退出」,也点一次 +- 确认没有残留:打开「活动监视器」,搜索 `TraceMemo`,有残留就选中并点「退出」 + +然后打开「终端」(`应用程序 → 实用工具 → 终端`),执行: + +```bash +tccutil reset SystemPolicyAppDataDetailed com.tracememo.app +``` + +再执行: + +```bash +tccutil reset SystemPolicyAllFiles com.tracememo.app +``` + +两条命令都只影响当前用户,不需要 `sudo`。 + +执行后**不会**看到「授权成功」之类的提示。这条命令的作用是**删掉旧记录**,不是**发放权限**。删除之后,需要你在系统设置里重新授权一次(见第 5 节)。 + +### 如果提示服务名无效 + +终端报下面这类错误: + +``` +tccutil: Invalid service name +``` + +说明当前系统不认识 `SystemPolicyAppDataDetailed` 这个服务名。改用 Apple 公开文档里的写法: + +```bash +tccutil reset SystemPolicyAppData com.tracememo.app +``` + +`SystemPolicyAppDataDetailed` 是否在所有 macOS 27 版本上都可用,尚未逐一验证。两种情况的效果一样:都是清掉 TraceMemo 在这类「其他应用数据」权限上的旧记录。无论用哪条,都还是要走第 5 节手动重新授权。 + +--- + +## 4. 两条命令分别管什么 + +| 命令 | 管的是 | 什么时候需要 | +| --- | --- | --- | +| `SystemPolicyAppDataDetailed`(或 `SystemPolicyAppData`) | 访问**其他应用沙盒容器内文件**的授权。微信数据正好在这个范围内 | 主要用这条。它清掉的是「读微信容器」这一层的旧记录 | +| `SystemPolicyAllFiles` | **完全磁盘访问权限**的授权记录 | 系统设置里 TraceMemo 的开关看起来是开的、但实际不生效时,用它清掉整条记录重来 | + +适用范围: + +- 两条都只针对 `com.tracememo.app` 这一个应用,不影响微信、不影响其他软件 +- 都只影响当前登录的 Mac 用户 +- 都只是**删除记录**,不会自动给权限,也不会把权限收得更紧 +- 不要在命令里用 `All`(例如 `tccutil reset All`)—— 那会清掉这台机器上**所有应用**的所有隐私授权,微信、输入法、录屏、麦克风全要重新授权一遍,代价远大于收益 +- 不要用 `sudo`。系统级重置需要重启、影响所有用户,和本文的场景无关 + +两条命令可以只执行第一条先试。第一条无效、或系统设置里的开关状态明显不对,再执行第二条。 + +--- + +## 5. 执行命令后手动重新授权 + +1. 打开 **系统设置 → 隐私与安全性 → 完全磁盘访问权限** + (不同系统版本的条目名称略有差异,位置都在「隐私与安全性」下) +2. 在列表里找到 **TraceMemo** + - 如果还在列表里:选中,点列表下方的 `−` 删除 + - 如果已经不在列表里:跳过这一步 +3. 点 `+`,在弹出的文件选择器里进入 **应用程序**,选中 **TraceMemo.app**,点「打开」 +4. 确认 TraceMemo 右侧的开关是**打开**状态 +5. **完全退出 TraceMemo 再重新打开**。授权只在应用下次启动时生效,当前正在运行的进程拿不到新权限 + +如果第 3 步选不到应用,或添加后开关立刻又关掉,先确认应用确实在 `/Applications/TraceMemo.app`,而不是在下载目录、挂载的 dmg 镜像里、或某个临时文件夹里。从 dmg 直接运行的副本每次挂载路径都不同,系统无法稳定记住授权。 + +--- + +## 6. 完全不使用终端的做法 + +不想碰终端也可以,只是机制上少了一步,成功率没有统计数据。 + +### 步骤 + +1. 完全退出 TraceMemo(`Command + Q`,再从活动监视器确认没有残留进程) +2. 打开 **系统设置 → 隐私与安全性 → 完全磁盘访问权限** +3. 在列表里选中 **TraceMemo**,点 `−` 删除 +4. 完全退出「系统设置」(`Command + Q`) +5. 重新打开「系统设置」,回到同一页面,点 `+`,添加 `/Applications/TraceMemo.app` +6. 确认开关已打开 +7. 重新启动 TraceMemo,回到连接页重试 + +### 局限性 + +- **删掉再添加,不一定能清掉底层旧记录**。系统设置里删的是可见条目,某些情况下底层的授权记录仍然存在且指向旧的应用指纹,界面看起来正常、实际依旧不生效。终端那两条命令做的正是清掉这一层。 +- **开关是开的,不等于权限生效**。系统偶尔会显示开关已开,但实际判定仍是拒绝。这时只能靠重置记录解决。 +- **没有「修复」按钮**。系统设置不提供「重新校验应用」这类操作,能做的只有删除和重新添加。 + +两步的分工要说清:终端命令负责**清掉旧记录**,本节负责**重新建立记录**。 + +- 只做本节:旧记录可能还在,界面看着正常、实际不生效。 +- 只做终端命令:记录被一起删掉,必须再走本节第 3 到 5 步添加回来,否则权限是空的。 +- 已收到的恢复反馈里,成功案例都是两步连着做的。 + +所以推荐顺序是:第 3 节命令 → 本节删除并重新添加 → 重启应用。 + +--- + +## 7. 如何重启并验证 + +授权改完必须**重启进程**,不是重新打开窗口。 + +### 从 Dock 退出 + +1. 在 Dock 里找到 TraceMemo 图标 +2. 右键(或双指点按)→ **退出** +3. 确认图标下方的运行指示点消失 +4. 重新点图标启动 + +### 从 Finder 退出 + +1. 打开「活动监视器」(`应用程序 → 实用工具 → 活动监视器`) +2. 搜索框输入 `TraceMemo` +3. 选中 `TraceMemo` 进程,点左上角的 `×`,选「退出」 +4. 确认列表里已经没有 TraceMemo +5. 打开「访达 → 应用程序」,双击 **TraceMemo** + +### 验证是否恢复 + +启动后回到连接页,看这几点: + +- 不再出现「无法读取微信数据库」 +- 账号、联系人、会话能正常加载 +- 随便搜一个关键词,能返回结果 + +只看到「已连接」但列表是空的,不算恢复,按第 8 节收集信息。 + +--- + +## 8. 修复失败要提供什么 + +按顺序做一遍,仍然失败,把下面这些信息一起提交: + +1. **系统版本**:苹果菜单 → 关于本机,记录版本号(例如 macOS 27.x)和芯片(Apple Silicon / Intel) +2. **TraceMemo 版本**:应用内「设置 → 关于」,或菜单栏 `TraceMemo → 关于 TraceMemo` +3. **微信版本**:微信 `设置 → 关于微信` +4. **连接页的完整提示原文**,包括错误码。有截图更好 +5. **脱敏诊断摘要**:连接页上的「复制脱敏诊断摘要」按钮,点一下会复制到剪贴板,直接粘贴到反馈里 +6. **第 3 节命令的实际输出**,包括报错。如果提示 `Invalid service name`,一定要写出来 +7. **系统设置里 TraceMemo 那条记录的状态**:在不在列表里、开关是开还是关 + +诊断摘要里不包含聊天内容、数据库密钥、完整文件路径,可以放心贴出来。 + +--- + +## 9. 不需要重新取密钥,也不要动微信数据 + +这一步很重要,能省掉大量无用操作。 + +- **不需要重新获取 WCDB 密钥**。密钥保存在本地,本次故障里它一直是正确的。重新走一遍密钥获取流程,只会多一次监听微信登录的动作,不会改变权限结果。 +- **不要删除微信数据库**。数据完好,删了就是真的没了。 +- **不要删除 TraceMemo 的配置目录**。里面有账号指向、密钥、索引,删掉要全部重来。 +- **不要用 `sudo` 运行 TraceMemo**。以 root 运行会换一个进程身份,权限判定更混乱,还会让配置文件属主变成 root,后续正常启动反而出问题。 +- **不要 `chmod` / `chown` 整个微信目录**。改了会影响微信自身的读写,属于制造新问题。 +- **不要为了这个问题关闭 SIP**。SIP 管的是系统完整性保护,和「某个应用能不能读另一个应用的容器」不是一回事。关闭 SIP 不解决这个权限判定,还会降低整机安全性。SIP 相关说明见[关闭 SIP 教程](../mac-disable-sip.md),那是密钥获取流程里的独立话题。 + +### 顺带区分:这不是 Frida 附加失败 + +两类问题长得像,处理方式完全不同: + +| | 数据库访问权限问题(本文) | 密钥获取/进程附加问题 | +| --- | --- | --- | +| 出现时机 | 已经连过、升级后重新打开 | 首次连接,或重新获取密钥时 | +| 界面提示 | 「无法读取微信数据库」`DATABASE_PERMISSION_DENIED` | 监听超时 `CAPTURE_TIMEOUT`、内存扫描失败,或提示无法绑定微信进程 | +| 数据目录检测 | 显示已检测到 | 通常在更早的步骤就失败 | +| 处理方向 | 系统设置里重新授权 | 检查微信是否停在登录页、是否需要管理员授权、微信版本是否适配 | + +如果你的现象是「点了自动获取密钥,一直等到超时」,那走的是右边一列,不是本文的权限问题。 + +--- + +## 10. 这只是当前故障的恢复方案 + +说清楚边界: + +- 本文解决的是**已经发生**的授权断裂,不改变应用的签名方式。 +- 只要发布包仍然是当前这种 ad-hoc 签名,**下一次更新后仍可能再次发生**。 +- 出现时,重复第 3 到 5 节即可,通常不需要重装、不需要重新取密钥。 +- 彻底解决需要发布端改用稳定的开发者签名并完成公证,这属于打包流程的改动,不在用户侧。 + +正常使用、没有出现问题的用户,不需要提前做任何权限设置。授权不是安装前置条件。 diff --git a/docs/user-guide/troubleshooting.md b/docs/user-guide/troubleshooting.md index 102b857..fb6f73e 100644 --- a/docs/user-guide/troubleshooting.md +++ b/docs/user-guide/troubleshooting.md @@ -25,9 +25,10 @@ 1. 数据目录是否指向当前登录账号,而不是旧备份或迁移前目录; 2. 微信版本是否属于当前代码面向的 4.x 数据结构; 3. 微信是否处于页面要求的登录/退出状态; -4. macOS 是否完成页面要求的授权; +4. macOS 是否完成页面要求的授权;如果是升级 macOS 或更新 TraceMemo 之后才失败的,按[权限恢复文档](./macos27-permission-recovery.md)处理,只打开开关通常不够; 5. 连接页面的诊断项是否明确指出密钥、账号或数据库问题; 6. macOS 上 Apple Silicon 与 Intel 使用不同的连接流程,按连接页面提示操作;两者都可以自动获取数据库密钥。 +7. 页面显示「Intel Mac 自动获取」但电脑是 Apple 芯片时,多半是装了 Intel 版,见[架构不匹配说明](../platform/macos.md#提示intel-mac-自动获取但电脑是-apple-芯片)。 重新输入密钥或断开连接不会删除微信原始数据库。macOS 的 SIP 和授权说明见[平台说明](../platform/macos.md)。 @@ -35,11 +36,14 @@ 这是**权限问题,不是文件缺失** —— 如果你在终端里能列出 `db_storage/session/session.db`,说明数据目录是完整的,只是 TraceMemo 这个进程读不到。 -macOS 27 及更高版本需要给 TraceMemo 授予「完全磁盘访问权限」。注意:**终端能读到文件不代表 TraceMemo 有权限** —— macOS 的隐私权限按应用进程的身份判定,两者走的是不同的授权。 +注意:**终端能读到文件不代表 TraceMemo 有权限** —— macOS 的隐私权限按应用进程的身份判定,两者走的是不同的授权。 -处理步骤见 [macOS 数据访问与系统权限 → 提示「无法读取微信数据库」时](../platform/macos.md#提示无法读取微信数据库时)。 +按出现时机分两种情况: -仍然失败时,记录 **macOS 版本、CPU 架构(Apple Silicon / Intel)、微信版本、TraceMemo 版本和页面错误提示**后 扫码 README 文档二维码进群提交消息, 或者提交 Issue。 +- **首次连接就没成功**:给 TraceMemo 授予「完全磁盘访问权限」即可,步骤见 [macOS 数据访问与系统权限 → 提示「无法读取微信数据库」时](../platform/macos.md#提示无法读取微信数据库时)。 +- **之前能用,升级 macOS 或更新 TraceMemo 之后才失败**:多数是旧授权记录对不上新版本的应用,只打开开关不够,需要先清掉旧记录再重新授权。完整步骤见[macOS 更新后读不到微信数据:权限恢复](./macos27-permission-recovery.md)。 + +仍然失败时,记录 **macOS 版本、CPU 架构(Apple Silicon / Intel)、微信版本、TraceMemo 版本和页面错误提示** 后,扫码 README 文档二维码进群反馈,或提交 Issue。连接页的「复制脱敏诊断摘要」可以直接提供这些环境信息。 ## 连接成功但没有联系人或消息 diff --git a/scripts/after-pack.cjs b/scripts/after-pack.cjs index 37f6cee..2c80cf8 100644 --- a/scripts/after-pack.cjs +++ b/scripts/after-pack.cjs @@ -551,6 +551,28 @@ function validateRuntimeBinaryArchitecture(filePath, platform, arch, label) { ) } +/** + * 打包目标架构必须与 Electron 主程序一致。 + * + * Electron 缓存残留另一架构时会静默产出「arm64 包 + x64 主程序」:这种包靠 Rosetta + * 仍能启动,于是被当成 Intel 机器、走错密钥流程。这里让它在打包阶段直接失败。 + */ +function validateElectronMainBinary(appOutDir, productName, platform, arch) { + if (platform !== 'darwin') return + const binaryPath = path.join(appOutDir, `${productName}.app`, 'Contents', 'MacOS', productName) + if (!existsSync(binaryPath)) { + throw new Error(`Missing Electron main binary: ${binaryPath}`) + } + const architectures = readBinaryArchitectures(binaryPath) + if (!architectures.length) { + throw new Error(`Electron main binary is not a Mach-O executable: ${binaryPath}`) + } + if (arch === 'universal' || architectures.includes(arch)) return + throw new Error( + `Electron main binary is ${architectures.join('/')} but this bundle targets ${arch}: ${binaryPath}` + ) +} + /** * The Intel Mac key helper is an x86_64 executable that only the x64 (or * universal) macOS bundle can run. Every other target — Apple Silicon macOS, @@ -746,6 +768,12 @@ exports.default = async function afterPack(context) { validateReaderSkillRuntime(runtimeResources) validateSilkWasmRuntime(runtimeResources) const ffmpegPath = validateFfmpegRuntime(runtimeResources, context.electronPlatformName) + validateElectronMainBinary( + context.appOutDir, + context.packager.appInfo.productFilename, + context.electronPlatformName, + arch + ) validateRuntimeBinaryArchitecture( ffmpegPath, context.electronPlatformName, @@ -800,6 +828,7 @@ exports.pruneIntelMacKeyTool = pruneIntelMacKeyTool exports.pruneForeignArchConnectors = pruneForeignArchConnectors exports.pruneForeignArchNativeRuntimes = pruneForeignArchNativeRuntimes exports.validateRuntimeBinaryArchitecture = validateRuntimeBinaryArchitecture +exports.validateElectronMainBinary = validateElectronMainBinary exports.findMacosHelperPaths = findMacosHelperPaths exports.isMacosCodeValid = isMacosCodeValid exports.signMacosHelpers = signMacosHelpers diff --git a/src/main/index.ts b/src/main/index.ts index c420059..f8419e0 100644 --- a/src/main/index.ts +++ b/src/main/index.ts @@ -76,6 +76,8 @@ import type { } from '../shared/image-insight' import type { SystemOcrCapability, SystemOcrRequest, SystemOcrResult } from '../shared/system-ocr' import { KeyServiceMac } from './key-service-mac' +import { getMacArchSnapshot } from './macos-arch' +import { shouldProbeIntelEnvironment } from '../shared/macos-arch' import { KeyService as KeyServiceWin } from './key-service-win' import * as chat from './services/chat-service' import { @@ -1772,11 +1774,18 @@ app.whenReady().then(async () => { ) const self = chat.getSelfAccountInfo() const settings = loadSettings() - const intelMac = process.platform === 'darwin' && process.arch === 'x64' + const arch = getMacArchSnapshot() + // 只有真正的 Intel Mac 才需要探测 Intel 运行环境。 + // Apple 芯片上的 x64 进程(Rosetta)不能走这条路径,否则每次刷新环境都会起一个 x86 子进程。 + const intelMac = shouldProbeIntelEnvironment(arch.macKeyFlow) const intelEnvironment = intelMac ? await keyServiceMac.getIntelEnvironmentStatus() : undefined const environment = { platform: process.platform, architecture: process.arch, + hardwareArchitecture: arch.hardwareArch, + underARM64Translation: arch.underARM64Translation, + macKeyFlow: arch.macKeyFlow, + archAnomalies: arch.anomalies, osVersion: getOsVersionLabel(), appVersion: `v${app.getVersion()}`, wechatVersion: await detectWechatVersion(), diff --git a/src/main/key-service-mac.ts b/src/main/key-service-mac.ts index 4131230..f469fb4 100644 --- a/src/main/key-service-mac.ts +++ b/src/main/key-service-mac.ts @@ -7,6 +7,8 @@ import { isValidDatabaseKey } from './database-key-store' import crypto from 'crypto' import { findResource, getResourceCandidates } from './resource-paths' import { detectWechatVersion } from './services/connection-diagnostics' +import { getMacArchSnapshot } from './macos-arch' +import { ARCH_MISMATCH_X64_ON_ARM_ERROR, shouldProbeIntelEnvironment } from '../shared/macos-arch' const execFileAsync = promisify(execFile) @@ -239,6 +241,15 @@ export class KeyServiceMac { fridaAvailable: boolean wechatAdhocSigned: boolean }> { + // 方法内部再守一道:调用方漏判时也不能起 x86 helper。 + if (!shouldProbeIntelEnvironment(getMacArchSnapshot().macKeyFlow)) { + return { + sipDisabled: false, + pythonAvailable: false, + fridaAvailable: false, + wechatAdhocSigned: false + } + } const payload = await this.runMacKeyTool( ['status', '--runtime-dir', this.getMacKeyRuntimeDir()], 15_000 @@ -254,7 +265,15 @@ export class KeyServiceMac { async installIntelKeyRuntime( onStatus?: (message: string) => void ): Promise<{ success: boolean; error?: string; code?: string }> { - if (process.platform !== 'darwin' || process.arch !== 'x64') { + const arch = getMacArchSnapshot() + if (arch.macKeyFlow === 'arch-mismatch') { + return { + success: false, + code: 'ARCH_MISMATCH_X64_ON_ARM', + error: ARCH_MISMATCH_X64_ON_ARM_ERROR + } + } + if (arch.macKeyFlow !== 'intel') { return { success: false, code: 'UNSUPPORTED_PLATFORM', error: '仅 Intel Mac 需要安装此运行环境' } } onStatus?.('正在准备连接环境,请保持网络连接…') @@ -354,12 +373,25 @@ export class KeyServiceMac { if (process.platform !== 'darwin') { return { success: false, error: '自动获取密钥目前仅支持 macOS' } } + // 架构判定排在 SIP 之前:不匹配时先说明「当前跑的是 Intel 版」, + // 不能让用户先看到 SIP 提示、关闭 SIP 之后才发现问题依旧。 + const arch = getMacArchSnapshot() + if (arch.macKeyFlow === 'arch-mismatch') { + return { + success: false, + code: 'ARCH_MISMATCH_X64_ON_ARM', + error: ARCH_MISMATCH_X64_ON_ARM_ERROR + } + } + if (arch.macKeyFlow === 'unsupported') { + return { success: false, error: '自动获取密钥目前仅支持 macOS' } + } if (await this.isSipEnabled()) { return { success: false, code: 'SIP_ENABLED', error: SIP_ENABLED_ERROR } } try { - if (process.arch === 'x64') { + if (arch.macKeyFlow === 'intel') { onStatus?.('Intel Mac 将通过 Frida 获取微信主密钥,请让微信停留在未登录界面') const result = await this.captureIntelDbKey(accountRoot, timeoutMs, onStatus) onStatus?.(result.success ? '密钥获取成功' : '密钥获取失败') diff --git a/src/main/macos-arch.ts b/src/main/macos-arch.ts new file mode 100644 index 0000000..5f7a01d --- /dev/null +++ b/src/main/macos-arch.ts @@ -0,0 +1,60 @@ +import { execFileSync } from 'node:child_process' +import { app } from 'electron' +import { buildMacArchSnapshot, type MacArchSnapshot, type MacHardwareArch } from '../shared/macos-arch' + +let cachedSnapshot: MacArchSnapshot | null = null + +/** + * `hw.optional.arm64` 是唯一可靠的硬件判据:它在 ARM 上恒为 1, + * 在 Intel 上不存在或为 0,且与进程是否被翻译无关。 + * + * 读不到时返回 `unknown`,由上层保留兼容路径 —— 不能猜测硬件, + * 猜错会让真正的 Intel Mac 被误拦。 + */ +function readHardwareArch(): MacHardwareArch { + try { + const stdout = execFileSync('/usr/sbin/sysctl', ['-n', 'hw.optional.arm64'], { + encoding: 'utf8', + timeout: 1000, + stdio: ['ignore', 'pipe', 'ignore'] + }) + const value = stdout.trim() + if (value === '1') return 'arm64' + if (value === '0') return 'x64' + return 'unknown' + } catch { + return 'unknown' + } +} + +function readTranslationFlag(platform: NodeJS.Platform): boolean { + if (platform !== 'darwin') return false + try { + return app.runningUnderARM64Translation === true + } catch { + return false + } +} + +/** + * 取当前进程的架构快照。 + * + * 结果缓存一次:调用方包括每次刷新连接页都会走的 `key:getEnvironment`, + * 缓存后 sysctl 只在首次执行,避免刷 UI 反复起子进程。 + */ +export function getMacArchSnapshot(): MacArchSnapshot { + if (cachedSnapshot) return cachedSnapshot + const platform = process.platform + cachedSnapshot = buildMacArchSnapshot({ + platform, + hardwareArch: platform === 'darwin' ? readHardwareArch() : 'unknown', + runtimeArch: process.arch, + underARM64Translation: readTranslationFlag(platform) + }) + return cachedSnapshot +} + +/** 仅供测试重置缓存;运行期不调用。 */ +export function resetMacArchSnapshotCache(): void { + cachedSnapshot = null +} diff --git a/src/main/services/ai-provider-service.ts b/src/main/services/ai-provider-service.ts index 6c190a8..85a74b6 100644 --- a/src/main/services/ai-provider-service.ts +++ b/src/main/services/ai-provider-service.ts @@ -96,7 +96,15 @@ export class AIProviderRequestError extends Error { constructor( message: string, - details: { status?: number; code?: unknown; type?: unknown; responseBody?: unknown; contentType?: string; elapsedMs?: number; htmlInsteadOfJson?: boolean } = {} + details: { + status?: number + code?: unknown + type?: unknown + responseBody?: unknown + contentType?: string + elapsedMs?: number + htmlInsteadOfJson?: boolean + } = {} ) { super(message) this.name = 'AIProviderRequestError' @@ -358,7 +366,10 @@ export class AIProviderService { try { if (options?.apiKey) throw new Error('Tool Calling 不支持 legacy provider 配置') const resolved = this.resolveProvider(options) - if (resolved.provider.type !== 'openai-compatible' || resolved.provider.advanced.apiProtocol === 'responses') { + if ( + resolved.provider.type !== 'openai-compatible' || + resolved.provider.advanced.apiProtocol === 'responses' + ) { throw new Error('当前 Provider 协议暂不支持 Tool Calling POC') } const result = await requestOpenAICompatibleWithTools( @@ -377,7 +388,8 @@ export class AIProviderService { success: false, error: safeAIError(error), timedOut, - htmlInsteadOfJson: error instanceof AIProviderRequestError ? Boolean(error.htmlInsteadOfJson) : false, + htmlInsteadOfJson: + error instanceof AIProviderRequestError ? Boolean(error.htmlInsteadOfJson) : false, ...(error instanceof AIProviderRequestError ? { ...(error.status !== undefined ? { errorStatus: error.status } : {}), @@ -638,7 +650,7 @@ function deepSeekProvider(baseUrl?: string, model?: string): AIProviderSummary { } ], defaultModel: modelId, - advanced: { timeoutMs: 120_000, temperature: 0.7, maxTokens: 4096, extraHeaders: {} }, + advanced: { timeoutMs: 120_000, temperature: 0.7, maxTokens: 40960, extraHeaders: {} }, hasApiKey: false, isDefault: true, status: 'untested' @@ -981,7 +993,12 @@ async function requestOpenAICompatibleWithTools( messages: Array>, tools: AIChatToolDefinition[], signal?: AbortSignal -): Promise<{ data: string; toolCalls: AIChatToolCall[]; usage?: AIRequestResult['usage']; elapsedMs?: number }> { +): Promise<{ + data: string + toolCalls: AIChatToolCall[] + usage?: AIRequestResult['usage'] + elapsedMs?: number +}> { const endpoint = provider.baseUrl.endsWith('/chat/completions') ? provider.baseUrl : `${provider.baseUrl.replace(/\/+$/, '')}/chat/completions` @@ -1013,7 +1030,8 @@ async function requestOpenAICompatibleWithTools( } if (!response.ok) { throw new AIProviderRequestError( - payload?.error?.message || (parseError ? safeAIError(parseError) : `AI 请求失败 (${response.status})`), + payload?.error?.message || + (parseError ? safeAIError(parseError) : `AI 请求失败 (${response.status})`), { status: timing.status, contentType: timing.contentType, @@ -1034,7 +1052,13 @@ async function requestOpenAICompatibleWithTools( toolCalls: (message?.tool_calls || []).flatMap((call, index) => { const name = call.function?.name if (!name) return [] - return [{ id: call.id || `tool-call-${index + 1}`, name, arguments: call.function?.arguments || '{}' }] + return [ + { + id: call.id || `tool-call-${index + 1}`, + name, + arguments: call.function?.arguments || '{}' + } + ] }), usage: toOpenAIUsage(payload.usage), elapsedMs: timing.elapsedMs diff --git a/src/renderer/src/components/DatabaseConnectionPage.tsx b/src/renderer/src/components/DatabaseConnectionPage.tsx index 43d42e0..3bf4705 100644 --- a/src/renderer/src/components/DatabaseConnectionPage.tsx +++ b/src/renderer/src/components/DatabaseConnectionPage.tsx @@ -136,8 +136,11 @@ export function DatabaseConnectionPage({ onClearKey }: DatabaseConnectionPageProps): React.ReactElement { const isMac = platform === 'darwin' - const isIntelMac = isMac && environment?.architecture === 'x64' - const isAppleSiliconMac = isMac && !isIntelMac + // 流程由主进程的 macKeyFlow 决定;只有旧版主进程不回传该字段时才回落到运行架构。 + const macKeyFlow = environment?.macKeyFlow + const isArchMismatch = isMac && macKeyFlow === 'arch-mismatch' + const isIntelMac = isMac && (macKeyFlow ? macKeyFlow === 'intel' : environment?.architecture === 'x64') + const isAppleSiliconMac = isMac && !isIntelMac && !isArchMismatch const defaultPath = isMac ? '~/Library/Containers/com.tencent.xinWeChat/Data/Library/Application Support/com.tencent.xinWeChat/' : 'C:\\Users\\...\\WeChat Files\\Msg' @@ -282,6 +285,21 @@ export function DatabaseConnectionPage({ {guideStep === 1 && ( <> + {isArchMismatch && ( +
+ 当前电脑使用 Apple 芯片,但你正在运行 Intel 版 TraceMemo。 +

这个版本无法使用当前的 Apple Silicon 自动获取密钥流程。

+

请下载并安装 arm64 版本,然后重新启动 TraceMemo。

+

已保存的微信数据库密钥无需重新获取。

+ + 前往 GitHub Releases 下载 arm64 版本 + +
+ )}
操作系统
@@ -420,7 +438,7 @@ export function DatabaseConnectionPage({ @@ -446,7 +464,11 @@ export function DatabaseConnectionPage({ )} {guideStep === 3 && ( - )} diff --git a/src/renderer/src/features/settings/database-key/DatabaseKeyAutoDetect.tsx b/src/renderer/src/features/settings/database-key/DatabaseKeyAutoDetect.tsx index dd8742e..49e3c58 100644 --- a/src/renderer/src/features/settings/database-key/DatabaseKeyAutoDetect.tsx +++ b/src/renderer/src/features/settings/database-key/DatabaseKeyAutoDetect.tsx @@ -25,8 +25,11 @@ export function DatabaseKeyAutoDetect({ const environment = state.environment const platform = environment?.platform || runtimePlatform const isMac = platform === 'darwin' - const isIntelMac = platform === 'darwin' && environment?.architecture === 'x64' - const isAppleSiliconMac = isMac && !isIntelMac + // 与连接页同源:读主进程给出的 macKeyFlow,不在这里重新推断硬件。 + const macKeyFlow = environment?.macKeyFlow + const isArchMismatch = isMac && macKeyFlow === 'arch-mismatch' + const isIntelMac = isMac && (macKeyFlow ? macKeyFlow === 'intel' : environment?.architecture === 'x64') + const isAppleSiliconMac = isMac && !isIntelMac && !isArchMismatch const supported = environment?.autoDetectSupported ?? (platform === 'win32' || isMac) const phases = isAppleSiliconMac ? MAC_LOGIN_PHASES : DEFAULT_PHASES if (!supported) { @@ -41,20 +44,43 @@ export function DatabaseKeyAutoDetect({ } return (
+ {isArchMismatch && ( +
+ 当前电脑使用 Apple 芯片,但你正在运行 Intel 版 TraceMemo。 +

这个版本无法使用当前的 Apple Silicon 自动获取密钥流程。

+

请下载并安装 arm64 版本,然后重新启动 TraceMemo。

+

已保存的微信数据库密钥无需重新获取。

+ + 前往 GitHub Releases 下载 arm64 版本 + +
+ )}
- {isIntelMac ? 'Intel Mac 自动获取' : isMac ? 'macOS 自动获取' : 'Windows 自动获取'} + {isArchMismatch + ? '架构不匹配' + : isIntelMac + ? 'Intel Mac 自动获取' + : isMac + ? 'macOS 自动获取' + : 'Windows 自动获取'}

- {isIntelMac - ? '请让微信停在未登录界面,按页面提示操作即可。' - : isAppleSiliconMac - ? '执行时会请求管理员授权;授权后在微信登录界面点击“登录”即可,已有登录凭据时通常不需要扫码。监听最长两分钟,结束后会明确显示结果。' - : 'TraceMemo 可在微信桌面端正在运行时,通过本机内存扫描尝试获取数据库密钥。'} + {isArchMismatch + ? '当前应用的运行架构与这台 Mac 的芯片不匹配,自动获取已停用。' + : isIntelMac + ? '请让微信停在未登录界面,按页面提示操作即可。' + : isAppleSiliconMac + ? '执行时会请求管理员授权;授权后在微信登录界面点击“登录”即可,已有登录凭据时通常不需要扫码。监听最长两分钟,结束后会明确显示结果。' + : 'TraceMemo 可在微信桌面端正在运行时,通过本机内存扫描尝试获取数据库密钥。'}

-
diff --git a/src/renderer/src/styles/chat.scss b/src/renderer/src/styles/chat.scss index 2e4ba71..0b17702 100644 --- a/src/renderer/src/styles/chat.scss +++ b/src/renderer/src/styles/chat.scss @@ -2158,6 +2158,36 @@ word-break: break-word; } +.database-login-arch-mismatch { + margin: 0 0 16px; + padding: 14px 16px; + border: 1px solid #f0c9a8; + border-radius: 10px; + background: #fff7ef; + color: #6b4a2f; + font-size: 12px; + line-height: 1.6; +} + +.database-login-arch-mismatch strong { + display: block; + margin-bottom: 6px; + color: #8a4b12; + font-size: 13px; +} + +.database-login-arch-mismatch p { + margin: 0 0 4px; +} + +.database-login-arch-mismatch a { + display: inline-block; + margin-top: 8px; + color: #8a4b12; + font-weight: 600; + text-decoration: underline; +} + .database-login-diagnostics { margin: 0; border-top: 1px solid #e2e7e4; diff --git a/src/shared/connection-diagnostics.ts b/src/shared/connection-diagnostics.ts index 3cf2417..a89394d 100644 --- a/src/shared/connection-diagnostics.ts +++ b/src/shared/connection-diagnostics.ts @@ -7,6 +7,13 @@ export function buildSafeDiagnosticSummary( `TraceMemo: ${environment.appVersion}`, `操作系统: ${environment.osVersion}`, ...(environment.architecture ? [`处理器架构: ${environment.architecture}`] : []), + ...(environment.hardwareArchitecture + ? [ + `硬件架构: ${environment.hardwareArchitecture}${ + environment.underARM64Translation ? '(Rosetta 转译)' : '' + }` + ] + : []), `微信客户端: ${environment.wechatVersion}`, `数据结构: ${environment.dataStructureVersion}`, `数据目录: ${environment.dataDirectoryDetected ? '已检测到' : '未检测到'}`, diff --git a/src/shared/database-key.ts b/src/shared/database-key.ts index 9a04c00..778c7df 100644 --- a/src/shared/database-key.ts +++ b/src/shared/database-key.ts @@ -1,3 +1,5 @@ +import type { MacHardwareArch, MacKeyFlow } from './macos-arch' + export type DatabaseKeyValidationCode = | 'INVALID_FORMAT' | 'DATABASE_OPEN_FAILED' @@ -66,7 +68,22 @@ export interface AccountDiscoveryResult { export interface DatabaseKeyEnvironment { platform: NodeJS.Platform + /** + * 进程运行架构(`process.arch`)。原生库按它选择,不要用硬件架构替换: + * Rosetta 下的 x64 进程无法加载 arm64 动态库。 + */ architecture?: string + /** CPU 实际架构,来自 `hw.optional.arm64`。 */ + hardwareArchitecture?: MacHardwareArch + /** 当前进程是否被 Rosetta 翻译。 */ + underARM64Translation?: boolean + /** + * 密钥流程的唯一判据。UI 读它,主进程分流也读它,避免两侧各自推断。 + * 缺省时 UI 回落到 `architecture`,用于主进程尚未提供该字段的场景。 + */ + macKeyFlow?: MacKeyFlow + /** 架构信号矛盾时的诊断标记,例如 `hardware_arch_unknown`。 */ + archAnomalies?: string[] osVersion: string appVersion: string wechatVersion: string diff --git a/src/shared/macos-arch.ts b/src/shared/macos-arch.ts new file mode 100644 index 0000000..61e764c --- /dev/null +++ b/src/shared/macos-arch.ts @@ -0,0 +1,80 @@ +/** + * macOS 硬件架构与密钥流程的判定规则。 + * + * 三个概念必须分开,混用会把 Apple Silicon 上的 x64 运行时当成 Intel 机器: + * + * - hardwareArch CPU 实际架构,来自 `hw.optional.arm64` + * - runtimeArch 当前 Electron 可执行文件的架构(`process.arch`) + * - underARM64Translation 该进程是否被 Rosetta 翻译 + * + * 密钥流程只能由这三者共同决定;原生库加载仍然只看 runtimeArch, + * 因为同一进程内不能混用 arm64 与 x86_64 代码。 + */ +export type MacHardwareArch = 'arm64' | 'x64' | 'unknown' + +export type MacKeyFlow = 'apple-silicon' | 'intel' | 'arch-mismatch' | 'unsupported' + +export interface MacArchSnapshot { + platform: NodeJS.Platform + hardwareArch: MacHardwareArch + runtimeArch: string + underARM64Translation: boolean + macKeyFlow: MacKeyFlow + /** 检测到的矛盾信号,仅用于诊断上报,不参与流程选择。 */ + anomalies: string[] +} + +export interface MacArchInput { + platform: NodeJS.Platform + hardwareArch: MacHardwareArch + runtimeArch: string + underARM64Translation: boolean +} + +export const ARCH_MISMATCH_X64_ON_ARM_ERROR = + '当前 Mac 使用 Apple 芯片,但 TraceMemo 正在运行 Intel 版本。请安装 Apple Silicon(arm64)版本后重试。' + +/** + * 判定顺序有约束,不能调整: + * + * 1. 转译标志排在 sysctl 之前 —— 它由内核按当前进程直接给出,比一次外部命令更可信。 + * 即使 sysctl 失败(hardwareArch 为 unknown),只要进程被翻译且运行 x64, + * 硬件就必然是 Apple 芯片,必须拦下。 + * 2. 硬件明确为 arm64 时,即使转译标志缺失,也不能走 Intel 流程 —— + * 那等于在 Apple 芯片上装 Intel 运行环境。 + * 3. 只有硬件为 x64 或无法确认、且未经转译的 x64 进程,才允许走 Intel 流程。 + * 无法确认时保留兼容路径,避免无故阻断真正的 Intel Mac。 + */ +export function resolveMacKeyFlow(input: MacArchInput): MacKeyFlow { + if (input.platform !== 'darwin') return 'unsupported' + if (input.runtimeArch === 'arm64') return 'apple-silicon' + if (input.runtimeArch !== 'x64') return 'unsupported' + if (input.underARM64Translation) return 'arch-mismatch' + if (input.hardwareArch === 'arm64') return 'arch-mismatch' + return 'intel' +} + +/** + * Intel 运行环境探测要起一个 x86 子进程,只在真正的 Intel Mac 上才有意义。 + * 其它流程(尤其 `arch-mismatch`)一律跳过,避免刷新连接页就拉起错误的 helper。 + */ +export function shouldProbeIntelEnvironment(flow: MacKeyFlow): boolean { + return flow === 'intel' +} + +export function buildMacArchSnapshot(input: MacArchInput): MacArchSnapshot { + const anomalies: string[] = [] + if (input.hardwareArch === 'unknown') anomalies.push('hardware_arch_unknown') + if (input.runtimeArch === 'arm64' && input.underARM64Translation) { + anomalies.push('translation_flag_with_native_arm64') + } + if (input.runtimeArch === 'x64' && input.hardwareArch === 'arm64' && !input.underARM64Translation) { + // 硬件是 ARM、进程是 x64、却无转译标志:信号矛盾。流程仍按 arch-mismatch, + // 这个名字只用于诊断,不参与判定。 + anomalies.push('x64_runtime_on_arm_without_translation_flag') + } + if (input.runtimeArch === 'x64' && input.underARM64Translation && input.hardwareArch !== 'arm64') { + anomalies.push('translation_flag_without_arm_hardware') + } + return { ...input, macKeyFlow: resolveMacKeyFlow(input), anomalies } +} diff --git a/tests/component/database-key-arch-mismatch.test.tsx b/tests/component/database-key-arch-mismatch.test.tsx new file mode 100644 index 0000000..362a509 --- /dev/null +++ b/tests/component/database-key-arch-mismatch.test.tsx @@ -0,0 +1,92 @@ +import { render, screen } from '@testing-library/react' +import { describe, expect, it, vi } from 'vitest' +import { DatabaseKeyAutoDetect } from '../../src/renderer/src/features/settings/database-key/DatabaseKeyAutoDetect' +import type { DatabaseKeyState } from '../../src/renderer/src/features/settings/database-key/types' +import type { DatabaseKeyEnvironment } from '../../src/shared/database-key' +import type { MacKeyFlow } from '../../src/shared/macos-arch' + +function environment(macKeyFlow: MacKeyFlow, hardwareArchitecture: 'arm64' | 'x64'): DatabaseKeyEnvironment { + return { + platform: 'darwin', + architecture: macKeyFlow === 'intel' ? 'x64' : 'x64', + hardwareArchitecture, + underARM64Translation: macKeyFlow === 'arch-mismatch', + macKeyFlow, + archAnomalies: [], + osVersion: 'macOS 15.7.7 (x64)', + appVersion: 'v2.5.3', + wechatVersion: '4.1.13', + dataStructureVersion: 'v4', + dataDirectoryDetected: true, + diagnosticSummary: 'fixture', + autoDetectSupported: true, + wechatRunning: true, + accountIdentified: true, + dbConnected: false, + encryptionAvailable: true + } +} + +function state(macKeyFlow: MacKeyFlow): DatabaseKeyState { + return { + status: 'idle', + saved: false, + encryptionAvailable: true, + autoPhase: 0, + environment: environment(macKeyFlow, macKeyFlow === 'intel' ? 'x64' : 'arm64') + } +} + +describe('DatabaseKeyAutoDetect arch mismatch', () => { + it('explains the mismatch and disables auto detection', () => { + render( + + ) + + expect( + screen.getByText('当前电脑使用 Apple 芯片,但你正在运行 Intel 版 TraceMemo。') + ).toBeTruthy() + expect(screen.getByText('已保存的微信数据库密钥无需重新获取。')).toBeTruthy() + expect(screen.getByText('架构不匹配')).toBeTruthy() + expect(screen.queryByText('Intel Mac 自动获取')).toBeNull() + expect((screen.getByRole('button', { name: '自动获取密钥' }) as HTMLButtonElement).disabled).toBe( + true + ) + }) + + it('keeps the Apple Silicon copy when the flow matches the hardware', () => { + render( + + ) + + expect(screen.getByText('macOS 自动获取')).toBeTruthy() + expect(screen.queryByText('当前电脑使用 Apple 芯片,但你正在运行 Intel 版 TraceMemo。')).toBeNull() + expect((screen.getByRole('button', { name: '自动获取密钥' }) as HTMLButtonElement).disabled).toBe( + false + ) + }) + + it('still labels a genuine Intel Mac as Intel', () => { + render( + + ) + + expect(screen.getByText('Intel Mac 自动获取')).toBeTruthy() + expect(screen.queryByText('架构不匹配')).toBeNull() + }) +}) diff --git a/tests/unit/after-pack-electron-arch.test.ts b/tests/unit/after-pack-electron-arch.test.ts new file mode 100644 index 0000000..5f5ad9a --- /dev/null +++ b/tests/unit/after-pack-electron-arch.test.ts @@ -0,0 +1,82 @@ +import { createRequire } from 'module' +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'fs' +import { tmpdir } from 'os' +import { join } from 'path' +import { afterAll, describe, expect, it } from 'vitest' + +const nodeRequire = createRequire(import.meta.url) +const { validateElectronMainBinary } = nodeRequire('../../scripts/after-pack.cjs') as { + validateElectronMainBinary: ( + appOutDir: string, + productName: string, + platform: string, + arch: string + ) => void +} + +const root = mkdtempSync(join(tmpdir(), 'tm-electron-arch-')) + +/** 最小 64 位 Mach-O 头;cputype 决定被判成哪种架构。 */ +function macho(cpuType: number): Buffer { + const buffer = Buffer.alloc(32) + buffer.writeUInt32LE(0xfeedfacf, 0) + buffer.writeUInt32LE(cpuType, 4) + return buffer +} + +const CPU_X86_64 = 0x01000007 +const CPU_ARM64 = 0x0100000c + +function bundle(name: string, binary: Buffer | string): { appOutDir: string; productName: string } { + const appOutDir = join(root, name) + const macosDir = join(appOutDir, 'TraceMemo.app', 'Contents', 'MacOS') + mkdirSync(macosDir, { recursive: true }) + writeFileSync(join(macosDir, 'TraceMemo'), binary) + return { appOutDir, productName: 'TraceMemo' } +} + +afterAll(() => rmSync(root, { recursive: true, force: true })) + +describe('validateElectronMainBinary', () => { + it('accepts an arm64 main binary for an arm64 bundle', () => { + const context = bundle('arm64-ok', macho(CPU_ARM64)) + expect(() => + validateElectronMainBinary(context.appOutDir, context.productName, 'darwin', 'arm64') + ).not.toThrow() + }) + + it('rejects an x64 Electron binary in an arm64 bundle', () => { + const context = bundle('arm64-with-x64', macho(CPU_X86_64)) + expect(() => + validateElectronMainBinary(context.appOutDir, context.productName, 'darwin', 'arm64') + ).toThrow(/is x64 but this bundle targets arm64/) + }) + + it('accepts either slice for a universal bundle', () => { + const context = bundle('universal', macho(CPU_X86_64)) + expect(() => + validateElectronMainBinary(context.appOutDir, context.productName, 'darwin', 'universal') + ).not.toThrow() + }) + + it('fails when the main binary is missing', () => { + const appOutDir = join(root, 'missing') + mkdirSync(join(appOutDir, 'TraceMemo.app', 'Contents', 'MacOS'), { recursive: true }) + expect(() => + validateElectronMainBinary(appOutDir, 'TraceMemo', 'darwin', 'arm64') + ).toThrow(/Missing Electron main binary/) + }) + + it('fails when the main binary is not a Mach-O executable', () => { + const context = bundle('not-macho', '#!/bin/sh\necho hi\n') + expect(() => + validateElectronMainBinary(context.appOutDir, context.productName, 'darwin', 'arm64') + ).toThrow(/not a Mach-O executable/) + }) + + it('ignores non-darwin targets', () => { + expect(() => + validateElectronMainBinary(join(root, 'nowhere'), 'TraceMemo', 'win32', 'x64') + ).not.toThrow() + }) +}) diff --git a/tests/unit/macos-arch.test.ts b/tests/unit/macos-arch.test.ts new file mode 100644 index 0000000..af663dd --- /dev/null +++ b/tests/unit/macos-arch.test.ts @@ -0,0 +1,247 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest' +import { KeyServiceMac } from '../../src/main/key-service-mac' +import { + ARCH_MISMATCH_X64_ON_ARM_ERROR, + buildMacArchSnapshot, + resolveMacKeyFlow, + shouldProbeIntelEnvironment, + type MacArchInput +} from '../../src/shared/macos-arch' + +/** + * 密钥流程的选择依据是「硬件 + 运行架构 + 转译状态」三者组合, + * 不是单一的 `process.arch`。这组用例把组合表钉死, + * 避免以后有人把判定简化回 `process.arch === 'x64'`。 + */ +function input(overrides: Partial): MacArchInput { + return { + platform: 'darwin', + hardwareArch: 'arm64', + runtimeArch: 'arm64', + underARM64Translation: false, + ...overrides + } +} + +describe('resolveMacKeyFlow', () => { + it('runs the Apple Silicon flow on native arm64', () => { + expect(resolveMacKeyFlow(input({}))).toBe('apple-silicon') + }) + + it('blocks the Intel flow when Rosetta is reported, even if hardware is unknown', () => { + expect( + resolveMacKeyFlow(input({ hardwareArch: 'unknown', runtimeArch: 'x64', underARM64Translation: true })) + ).toBe('arch-mismatch') + }) + + it('blocks the Intel flow when hardware is arm64 but the translation flag is missing', () => { + expect( + resolveMacKeyFlow(input({ hardwareArch: 'arm64', runtimeArch: 'x64', underARM64Translation: false })) + ).toBe('arch-mismatch') + }) + + it('keeps the Intel flow on a real Intel Mac', () => { + expect( + resolveMacKeyFlow(input({ hardwareArch: 'x64', runtimeArch: 'x64', underARM64Translation: false })) + ).toBe('intel') + }) + + it('falls back to the Intel flow when hardware cannot be read but nothing looks translated', () => { + expect( + resolveMacKeyFlow(input({ hardwareArch: 'unknown', runtimeArch: 'x64', underARM64Translation: false })) + ).toBe('intel') + }) + + it('treats other platforms as unsupported', () => { + expect( + resolveMacKeyFlow(input({ platform: 'win32', hardwareArch: 'x64', runtimeArch: 'x64' })) + ).toBe('unsupported') + }) + + it('treats an unexpected runtime architecture as unsupported', () => { + expect(resolveMacKeyFlow(input({ runtimeArch: 'ia32' }))).toBe('unsupported') + }) +}) + +describe('buildMacArchSnapshot', () => { + it('records the unknown hardware signal without changing the Intel flow', () => { + const snapshot = buildMacArchSnapshot( + input({ hardwareArch: 'unknown', runtimeArch: 'x64', underARM64Translation: false }) + ) + expect(snapshot.macKeyFlow).toBe('intel') + expect(snapshot.anomalies).toContain('hardware_arch_unknown') + }) + + it('records a translated process whose hardware probe disagreed', () => { + const snapshot = buildMacArchSnapshot( + input({ hardwareArch: 'x64', runtimeArch: 'x64', underARM64Translation: true }) + ) + expect(snapshot.macKeyFlow).toBe('arch-mismatch') + expect(snapshot.anomalies).toContain('translation_flag_without_arm_hardware') + }) + + it('records a translation flag on a native arm64 process', () => { + const snapshot = buildMacArchSnapshot(input({ underARM64Translation: true })) + expect(snapshot.macKeyFlow).toBe('apple-silicon') + expect(snapshot.anomalies).toContain('translation_flag_with_native_arm64') + }) + + it('flags an x64 runtime on Apple silicon that reports no translation', () => { + const snapshot = buildMacArchSnapshot( + input({ hardwareArch: 'arm64', runtimeArch: 'x64', underARM64Translation: false }) + ) + expect(snapshot.macKeyFlow).toBe('arch-mismatch') + expect(snapshot.anomalies).toContain('x64_runtime_on_arm_without_translation_flag') + }) +}) + +describe('ARCH_MISMATCH_X64_ON_ARM_ERROR', () => { + it('tells the user to install the arm64 build', () => { + expect(ARCH_MISMATCH_X64_ON_ARM_ERROR).toContain('Apple Silicon') + expect(ARCH_MISMATCH_X64_ON_ARM_ERROR).toContain('arm64') + }) +}) + +describe('shouldProbeIntelEnvironment', () => { + it('only probes on a genuine Intel Mac', () => { + expect(shouldProbeIntelEnvironment('intel')).toBe(true) + expect(shouldProbeIntelEnvironment('apple-silicon')).toBe(false) + expect(shouldProbeIntelEnvironment('arch-mismatch')).toBe(false) + expect(shouldProbeIntelEnvironment('unsupported')).toBe(false) + }) +}) + +const { spawnMock, execFileMock, flowState } = vi.hoisted(() => ({ + spawnMock: vi.fn(), + execFileMock: vi.fn(), + flowState: { flow: 'arch-mismatch' as 'apple-silicon' | 'intel' | 'arch-mismatch' | 'unsupported' } +})) + +vi.mock('child_process', () => ({ + spawn: (...args: unknown[]) => spawnMock(...args), + execFile: (...args: unknown[]) => execFileMock(...args) +})) + +vi.mock('electron', () => ({ + app: { + getPath: () => '/tmp/tracememo-fixture-userdata', + getVersion: () => '0.0.0', + isPackaged: false + }, + safeStorage: { + isEncryptionAvailable: () => false, + encryptString: () => Buffer.from(''), + decryptString: () => '' + } +})) + +vi.mock('../../src/main/macos-arch', () => ({ + getMacArchSnapshot: () => ({ + platform: 'darwin', + hardwareArch: flowState.flow === 'intel' ? 'x64' : 'arm64', + runtimeArch: flowState.flow === 'intel' ? 'x64' : 'x64', + underARM64Translation: flowState.flow === 'arch-mismatch', + macKeyFlow: flowState.flow, + anomalies: [] + }), + resetMacArchSnapshotCache: () => undefined +})) + +describe('KeyServiceMac arch guard', () => { + beforeEach(() => { + spawnMock.mockReset() + execFileMock.mockReset() + flowState.flow = 'arch-mismatch' + }) + + /** 列出所有被 spawn/execFile 触达的可执行文件,用于断言「什么也没启动」。 */ + const execFileCommands = (): string[] => execFileMock.mock.calls.map((call) => String(call[0])) + + it('returns ARCH_MISMATCH_X64_ON_ARM without spawning anything', async () => { + const service = new KeyServiceMac() + const result = await service.autoGetDbKey(undefined, 60_000, '/tmp/fixture-account') + + expect(result.success).toBe(false) + expect(result.code).toBe('ARCH_MISMATCH_X64_ON_ARM') + expect(result.error).toBe(ARCH_MISMATCH_X64_ON_ARM_ERROR) + expect(spawnMock).not.toHaveBeenCalled() + expect(execFileMock).not.toHaveBeenCalled() + }) + + it('never touches csrutil, pgrep or osascript on a mismatched machine', async () => { + const service = new KeyServiceMac() + await service.autoGetDbKey(undefined, 60_000, '/tmp/fixture-account') + + const commands = execFileCommands() + // csrutil = SIP 探测,pgrep = 查找微信进程,osascript = 请求管理员授权执行 helper + expect(commands).not.toContain('/usr/bin/csrutil') + expect(commands).not.toContain('/usr/bin/pgrep') + expect(commands).not.toContain('/usr/bin/osascript') + expect(spawnMock).not.toHaveBeenCalled() + }) + + it('checks the architecture before SIP, so a mismatch never reports SIP_ENABLED', async () => { + execFileMock.mockImplementation((_cmd, _args, _options, callback) => { + callback(null, { stdout: 'System Integrity Protection status: enabled.' }, '') + }) + + const service = new KeyServiceMac() + const result = await service.autoGetDbKey(undefined, 60_000, '/tmp/fixture-account') + + expect(result.code).toBe('ARCH_MISMATCH_X64_ON_ARM') + expect(result.code).not.toBe('SIP_ENABLED') + expect(execFileMock).not.toHaveBeenCalled() + }) + + it('refuses to install the Intel runtime on a mismatched machine', async () => { + const service = new KeyServiceMac() + const result = await service.installIntelKeyRuntime() + + expect(result.success).toBe(false) + expect(result.code).toBe('ARCH_MISMATCH_X64_ON_ARM') + expect(spawnMock).not.toHaveBeenCalled() + }) + + it('does not spawn the Intel helper when refreshing the environment', async () => { + const service = new KeyServiceMac() + const status = await service.getIntelEnvironmentStatus() + + expect(status).toEqual({ + sipDisabled: false, + pythonAvailable: false, + fridaAvailable: false, + wechatAdhocSigned: false + }) + expect(spawnMock).not.toHaveBeenCalled() + }) + + it('still reports SIP_ENABLED on a genuine Intel Mac', async () => { + flowState.flow = 'intel' + // promisify(execFile) 在只传两个参数时把 callback 放在第三个位置。 + execFileMock.mockImplementation((_cmd, _args, options, callback) => { + const done = typeof options === 'function' ? options : callback + done(null, { stdout: 'System Integrity Protection status: enabled.' }, '') + }) + + const service = new KeyServiceMac() + const result = await service.autoGetDbKey(undefined, 60_000, '/tmp/fixture-account') + + expect(result.code).toBe('SIP_ENABLED') + expect(spawnMock).not.toHaveBeenCalled() + }) + + it('never reaches the Intel helper on the Apple Silicon flow', async () => { + flowState.flow = 'apple-silicon' + execFileMock.mockImplementation((_cmd, _args, options, callback) => { + const done = typeof options === 'function' ? options : callback + done(null, { stdout: '' }, '') + }) + + const service = new KeyServiceMac() + const result = await service.autoGetDbKey(undefined, 60_000, '/tmp/fixture-account') + + expect(result.code).not.toBe('ARCH_MISMATCH_X64_ON_ARM') + // Intel helper 是唯一的 spawn 调用点;arm64 流程走 osascript + xkey_helper,不会经过它。 + expect(spawnMock).not.toHaveBeenCalled() + }) +})