fix: mac arm通过文件夹打开被判定为intel芯片

mac os升级27 权限问题解决文档
This commit is contained in:
Wxw-Gu committed 2026-11-06 11:10:01 +08:00
1 parent 80e0f43529
commit 05b881d79e
18 files changed
+1066 -29

No files matched your search

+10 -1
View File
@@ -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(),
+34 -2
View File
@@ -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 ? '密钥获取成功' : '密钥获取失败')
+60
View File
@@ -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
}
+31 -7
View File
@@ -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<Record<string, unknown>>,
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
@@ -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({
</div>
{guideStep === 1 && (
<>
{isArchMismatch && (
<div className="database-login-arch-mismatch" role="alert">
<strong>当前电脑使用 Apple 芯片,但你正在运行 Intel 版 TraceMemo。</strong>
<p>这个版本无法使用当前的 Apple Silicon 自动获取密钥流程。</p>
<p>请下载并安装 arm64 版本,然后重新启动 TraceMemo。</p>
<p>已保存的微信数据库密钥无需重新获取。</p>
<a
href="https://github.com/Wxw-Gu/TraceMemo/releases"
target="_blank"
rel="noreferrer"
>
前往 GitHub Releases 下载 arm64 版本
</a>
</div>
)}
<dl className="database-login-diagnostics">
<div>
<dt>操作系统</dt>
@@ -420,7 +438,7 @@ export function DatabaseConnectionPage({
<Button
className="database-login-primary"
onClick={onGuideNext}
disabled={!selectedAccountId}
disabled={!selectedAccountId || isArchMismatch}
>
检查完成,继续
</Button>
@@ -446,7 +464,11 @@ export function DatabaseConnectionPage({
</Button>
)}
{guideStep === 3 && (
<Button className="database-login-primary" onClick={onAutoGetKey}>
<Button
className="database-login-primary"
onClick={onAutoGetKey}
disabled={isArchMismatch}
>
{isMac ? '开始获取密钥' : '开始准备连接组件'}
</Button>
)}
@@ -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 (
<section className="settings-card database-key-auto">
{isArchMismatch && (
<div className="database-login-arch-mismatch" role="alert">
<strong>当前电脑使用 Apple 芯片,但你正在运行 Intel 版 TraceMemo。</strong>
<p>这个版本无法使用当前的 Apple Silicon 自动获取密钥流程。</p>
<p>请下载并安装 arm64 版本,然后重新启动 TraceMemo。</p>
<p>已保存的微信数据库密钥无需重新获取。</p>
<a href="https://github.com/Wxw-Gu/TraceMemo/releases" target="_blank" rel="noreferrer">
前往 GitHub Releases 下载 arm64 版本
</a>
</div>
)}
<div className="database-key-auto-heading">
<div>
<strong>
{isIntelMac ? 'Intel Mac 自动获取' : isMac ? 'macOS 自动获取' : 'Windows 自动获取'}
{isArchMismatch
? '架构不匹配'
: isIntelMac
? 'Intel Mac 自动获取'
: isMac
? 'macOS 自动获取'
: 'Windows 自动获取'}
</strong>
<p>
{isIntelMac
? '请让微信停在未登录界面,按页面提示操作即可。'
: isAppleSiliconMac
? '执行时会请求管理员授权;授权后在微信登录界面点击“登录”即可,已有登录凭据时通常不需要扫码。监听最长两分钟,结束后会明确显示结果。'
: 'TraceMemo 可在微信桌面端正在运行时,通过本机内存扫描尝试获取数据库密钥。'}
{isArchMismatch
? '当前应用的运行架构与这台 Mac 的芯片不匹配,自动获取已停用。'
: isIntelMac
? '请让微信停在未登录界面,按页面提示操作即可。'
: isAppleSiliconMac
? '执行时会请求管理员授权;授权后在微信登录界面点击“登录”即可,已有登录凭据时通常不需要扫码。监听最长两分钟,结束后会明确显示结果。'
: 'TraceMemo 可在微信桌面端正在运行时,通过本机内存扫描尝试获取数据库密钥。'}
</p>
</div>
<Button variant="outline" onClick={onDetect} disabled={disabled}>
<Button
variant="outline"
onClick={onDetect}
disabled={disabled || isArchMismatch}
>
{state.status === 'auto-detecting' ? '正在获取…' : '自动获取密钥'}
</Button>
</div>
+30
View File
@@ -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;
+7
View File
@@ -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 ? '已检测到' : '未检测到'}`,
+17
View File
@@ -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
+80
View File
@@ -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 }
}