diff --git a/.gitignore b/.gitignore index e00ab35..077e595 100644 --- a/.gitignore +++ b/.gitignore @@ -28,5 +28,6 @@ progress.md task_plan.md *tm-wcdb-config-helper* +*libtmlicense* debug-originals /build/mac-staging/ diff --git a/docs/development/mac-wechat-send-capability-integration.md b/docs/development/mac-wechat-send-capability-integration.md new file mode 100644 index 0000000..3bbf7a4 --- /dev/null +++ b/docs/development/mac-wechat-send-capability-integration.md @@ -0,0 +1,28 @@ +# macOS 版本发送能力二次开发 + +如果你已经拥有 TraceMemo 发送能力授权,并希望基于源码进行二次开发,请联系授权人获取开发环境所需的发送能力组件包。 + +## 1. 安装发送能力组件 + +获取组件包后,将以下文件放到项目对应目录: + +| 组件 | 放入目录 | +| ----------------------- | --------------------------------- | +| `tm-wechat-host` | `resources/runtime/darwin-arm64/` | +| `libtmwechat.dylib` | `resources/runtime/darwin-arm64/` | +| `runtime-manifest.json` | `resources/runtime/darwin-arm64/` | +| `libwcdb_api.dylib` | `resources/wcdb/macos/arm64/` | +| `libWCDB.dylib` | `resources/wcdb/macos/arm64/` | +| `tm-wcdb-config-helper` | `resources/wcdb/macos/arm64/` | +| `libtmlicense.dylib` | `resources/wcdb/macos/arm64/` | + +完成后,为以下两个文件添加执行权限: + +```bash +chmod 755 resources/runtime/darwin-arm64/tm-wechat-host +chmod 755 resources/wcdb/macos/arm64/tm-wcdb-config-helper +``` + +完成配置后,启动 TraceMemo 开发环境,在「设置 → 微信发送」中查看发送能力与授权状态。 + +**注意:** 发送能力组件不包含授权。开发环境仍需使用有效的设备授权才能绑定微信和发送消息。 diff --git a/resources/wcdb/macos/arm64/libwcdb_api.dylib b/resources/wcdb/macos/arm64/libwcdb_api.dylib index eda2136..242725f 100755 Binary files a/resources/wcdb/macos/arm64/libwcdb_api.dylib and b/resources/wcdb/macos/arm64/libwcdb_api.dylib differ diff --git a/scripts/after-pack.cjs b/scripts/after-pack.cjs index 202e9be..37f6cee 100644 --- a/scripts/after-pack.cjs +++ b/scripts/after-pack.cjs @@ -29,6 +29,7 @@ const MACOS_EDITION_CODE_PATHS = [ ['wcdb', 'macos', 'arm64', 'libwcdb_api.dylib'], ['wcdb', 'macos', 'arm64', 'libWCDB.dylib'], ['wcdb', 'macos', 'arm64', 'tm-wcdb-config-helper'], + ['wcdb', 'macos', 'arm64', 'libtmlicense.dylib'], ['runtime', 'darwin-arm64', 'tm-wechat-host'], ['runtime', 'darwin-arm64', 'libtmwechat.dylib'] ] @@ -124,9 +125,21 @@ function validateMacEditionResources(runtimeResources, edition, platform) { .split(/\r?\n/) .map((line) => line.trim().split(/\s+/).pop() || '') .map((symbol) => symbol.replace(/^_/, '')) - const hasNativeAbi = symbols.some((symbol) => symbol.startsWith('wcdb_msg_insert_')) - if ((edition === 'public' && hasNativeAbi) || (edition === 'native' && !hasNativeAbi)) { - throw new Error(`Bundled WCDB API has the wrong ${edition} ABI`) + // OSS 合法保留的只读消息插入状态查询符号;其余 wcdb_msg_insert_* 都是写入入口。 + const PUBLIC_READONLY_MSG_INSERT = new Set([ + 'wcdb_msg_insert_get_switches', + 'wcdb_msg_insert_inspect_shard', + 'wcdb_msg_insert_list_shard_catalog', + 'wcdb_msg_insert_get_rooms_status' + ]) + const msgInsertSymbols = symbols.filter((symbol) => symbol.startsWith('wcdb_msg_insert_')) + if (edition === 'public') { + const leaked = msgInsertSymbols.filter((symbol) => !PUBLIC_READONLY_MSG_INSERT.has(symbol)) + if (leaked.length) { + throw new Error(`Bundled public WCDB API leaks write ABI: ${leaked.join(', ')}`) + } + } else if (msgInsertSymbols.length === 0) { + throw new Error('Bundled native WCDB API is missing message-insert ABI') } const nativeInput = marker.nativeInput || {} if (edition === 'public') { @@ -216,14 +229,19 @@ function validateMacEditionResources(runtimeResources, edition, platform) { } } const stagedFiles = marker.nativeInput?.files - if (!Array.isArray(stagedFiles) || stagedFiles.length !== 6) { + if (!Array.isArray(stagedFiles) || stagedFiles.length !== 7) { throw new Error('Native build marker is missing its source Bundle file hashes') } for (const entry of stagedFiles) { const remainder = entry.path.replace(/^tracememo\//, '') - const relative = remainder.startsWith('runtime/') - ? remainder.replace(/^runtime\//, 'runtime/darwin-arm64/') - : path.join('wcdb', 'macos', 'arm64', remainder.replace(/^wcdb\//, '')) + let relative + if (remainder === 'runtime/libtmlicense.dylib') { + relative = path.join('wcdb', 'macos', 'arm64', 'libtmlicense.dylib') + } else if (remainder.startsWith('runtime/')) { + relative = remainder.replace(/^runtime\//, 'runtime/darwin-arm64/') + } else { + relative = path.join('wcdb', 'macos', 'arm64', remainder.replace(/^wcdb\//, '')) + } const binary = path.join(resources, relative) if (!existsSync(binary) || readFileSync(binary).length !== entry.bytes) { throw new Error(`Native packaged artifact size mismatch: ${entry.path}`) diff --git a/scripts/prepare-macos-edition.cjs b/scripts/prepare-macos-edition.cjs index 0c728c1..5d6d3d8 100644 --- a/scripts/prepare-macos-edition.cjs +++ b/scripts/prepare-macos-edition.cjs @@ -9,8 +9,8 @@ const { readBinaryArchitectures } = require('./binary-arch.cjs') const ROOT = path.resolve(__dirname, '..') const WCDB_DIST_ROOT = resolveWcdbDistRoot() -const NATIVE_DIST_ROOT = process.env.TRACEMEMO_NATIVE_DIST_ROOT || - path.resolve(ROOT, '..', 'native-runtime-dist') +const NATIVE_DIST_ROOT = + process.env.TRACEMEMO_NATIVE_DIST_ROOT || path.resolve(ROOT, '..', 'native-runtime-dist') const NATIVE_BUNDLE_ROOT = findNativeBundleRoot(NATIVE_DIST_ROOT) const PUBLIC_FILES = [ 'icon.png', @@ -42,8 +42,18 @@ const REQUIRED_NATIVE_SYMBOLS = [ const REQUIRED_PUBLIC_SYMBOLS = [ 'wcdb_get_messages', 'wcdb_get_group_members_batch', - 'wcdb_start_monitor_pipe' + 'wcdb_start_monitor_pipe', + 'wcdb_msg_insert_get_switches', + 'wcdb_msg_insert_inspect_shard', + 'wcdb_msg_insert_list_shard_catalog', + 'wcdb_msg_insert_get_rooms_status' ] +const PUBLIC_ALLOWED_MSG_INSERT = new Set([ + 'wcdb_msg_insert_get_switches', + 'wcdb_msg_insert_inspect_shard', + 'wcdb_msg_insert_list_shard_catalog', + 'wcdb_msg_insert_get_rooms_status' +]) const PROTECTED_RESOURCE_PATHS = ['runtime/runtime.zip'] function sha256(filePath) { @@ -69,7 +79,11 @@ function findNativeBundleRoot(root) { if (fs.existsSync(manifest)) { try { const parsed = JSON.parse(fs.readFileSync(manifest, 'utf8')) - if (parsed.platform === 'macos' && parsed.architecture === 'arm64' && Array.isArray(parsed.files)) { + if ( + parsed.platform === 'macos' && + parsed.architecture === 'arm64' && + Array.isArray(parsed.files) + ) { return directory } } catch { @@ -78,7 +92,8 @@ function findNativeBundleRoot(root) { } if (depth >= 3) continue for (const entry of fs.readdirSync(directory, { withFileTypes: true })) { - if (entry.isDirectory()) pending.push({ directory: path.join(directory, entry.name), depth: depth + 1 }) + if (entry.isDirectory()) + pending.push({ directory: path.join(directory, entry.name), depth: depth + 1 }) } } return root @@ -116,9 +131,17 @@ function validateWcdbPair(apiPath, dependencyPath, profile) { const missing = (profile === 'public' ? REQUIRED_PUBLIC_SYMBOLS : REQUIRED_NATIVE_SYMBOLS).filter( (symbol) => !symbols.includes(symbol) ) - if (missing.length) throw new Error(`${profile} WCDB API is missing exports: ${missing.join(', ')}`) - if (profile === 'public' && symbols.some((symbol) => symbol.startsWith('wcdb_msg_insert_'))) { - throw new Error('Public WCDB API contains native message-insert exports') + if (missing.length) + throw new Error(`${profile} WCDB API is missing exports: ${missing.join(', ')}`) + if (profile === 'public') { + const leaked = symbols.filter( + (symbol) => symbol.startsWith('wcdb_msg_insert_') && !PUBLIC_ALLOWED_MSG_INSERT.has(symbol) + ) + if (leaked.length) { + throw new Error( + `Public WCDB API contains forbidden message-insert exports: ${leaked.join(', ')}` + ) + } } const dependencies = run('/usr/bin/otool', ['-L', apiPath]) if (!dependencies.includes('@loader_path/libWCDB.dylib')) { @@ -132,13 +155,19 @@ function readAndValidateNativeManifest(bundleRoot) { if (manifest.platform !== 'macos' || manifest.architecture !== 'arm64') { throw new Error('Native bundle manifest must target macos-arm64') } - if (!Array.isArray(manifest.files) || manifest.files.length !== 6) { - throw new Error('Native bundle manifest must list exactly six files') + if (!Array.isArray(manifest.files) || manifest.files.length !== 7) { + throw new Error( + 'Native bundle manifest must list exactly seven files (six runtime/wcdb artifacts plus libtmlicense.dylib)' + ) } const normalized = new Set() const listedNativePaths = new Set() for (const entry of manifest.files) { - if (!entry || typeof entry.path !== 'string' || !/^tracememo\/(runtime|wcdb)\//.test(entry.path)) { + if ( + !entry || + typeof entry.path !== 'string' || + !/^tracememo\/(runtime|wcdb)\//.test(entry.path) + ) { throw new Error('Native bundle manifest contains an unexpected resource path') } if (normalized.has(entry.path) || !/^[a-f0-9]{64}$/.test(entry.sha256 || '')) { @@ -151,10 +180,16 @@ function readAndValidateNativeManifest(bundleRoot) { throw new Error(`Native bundle manifest verification failed: ${entry.path}`) } listedNativePaths.add(entry.path) - if (/\/runtime\/(tm-wechat-host|libtmwechat\.dylib)$/.test(entry.path)) { + if (/\/runtime\/(tm-wechat-host|libtmwechat\.dylib|libtmlicense\.dylib)$/.test(entry.path)) { if (!binaryArchitectures(source).includes('arm64')) { throw new Error(`Native runtime binary is not arm64: ${entry.path}`) } + if (entry.path.endsWith('libtmlicense.dylib')) { + const signature = run('/usr/bin/codesign', ['--verify', '--strict', source]) + if (signature.trim() !== '') { + throw new Error(`libtmlicense.dylib code signature is invalid: ${signature.trim()}`) + } + } } if (/\/wcdb\/(libwcdb_api\.dylib|tm-wcdb-config-helper)$/.test(entry.path)) { if (!binaryArchitectures(source).includes('arm64')) { @@ -163,6 +198,7 @@ function readAndValidateNativeManifest(bundleRoot) { } } const expected = [ + 'tracememo/runtime/libtmlicense.dylib', 'tracememo/runtime/libtmwechat.dylib', 'tracememo/runtime/runtime-manifest.json', 'tracememo/runtime/tm-wechat-host', @@ -173,7 +209,8 @@ function readAndValidateNativeManifest(bundleRoot) { if (expected.some((entry) => !normalized.has(entry))) { throw new Error('Native bundle manifest file list is incomplete') } - if (listedNativePaths.size !== expected.length) throw new Error('Native bundle manifest has unexpected files') + if (listedNativePaths.size !== expected.length) + throw new Error('Native bundle manifest has unexpected files') return { manifest, files: manifest.files } } @@ -189,10 +226,21 @@ function validateNativeBundle(bundleRoot, files) { const host = bySuffix('/runtime/tm-wechat-host') const runtimeDylib = bySuffix('/runtime/libtmwechat.dylib') const runtimeManifestPath = bySuffix('/runtime/runtime-manifest.json') + const licenseDylib = bySuffix('/runtime/libtmlicense.dylib') validateWcdbPair(api, companion, 'native') - for (const [binary, label] of [[helper, 'WCDB helper'], [host, 'WeChat host'], [runtimeDylib, 'WeChat runtime']]) { + for (const [binary, label] of [ + [helper, 'WCDB helper'], + [host, 'WeChat host'], + [runtimeDylib, 'WeChat runtime'], + [licenseDylib, 'License core'] + ]) { assertArm64(binary, label) } + // libtmlicense must carry a valid ad-hoc signature; it is dlopen'd at runtime. + const licenseSignature = run('/usr/bin/codesign', ['--verify', '--strict', licenseDylib]) + if (licenseSignature.trim() !== '') { + throw new Error(`libtmlicense.dylib code signature is invalid: ${licenseSignature.trim()}`) + } if (!run('/usr/bin/otool', ['-L', helper]).includes('@loader_path/libwcdb_api.dylib')) { throw new Error('WCDB helper does not resolve its API dylib via @loader_path') } @@ -202,37 +250,55 @@ function validateNativeBundle(bundleRoot, files) { throw new Error('Native bundle manifest does not declare the expected WCDB ABI') } const runtimeManifest = JSON.parse(fs.readFileSync(runtimeManifestPath, 'utf8')) - if (runtimeManifest.platform !== 'darwin-arm64' || runtimeManifest.architecture !== 'arm64' || runtimeManifest.protocolVersion !== 1) { + if ( + runtimeManifest.platform !== 'darwin-arm64' || + runtimeManifest.architecture !== 'arm64' || + runtimeManifest.protocolVersion !== 1 + ) { throw new Error('Runtime manifest platform, architecture, or protocol is invalid') } if (runtimeManifest.runtime !== 'tm-wechat-native') throw new Error('Runtime name is invalid') - if (!Array.isArray(runtimeManifest.supportedWechatVersions) || runtimeManifest.supportedWechatVersions.length === 0) { + if ( + !Array.isArray(runtimeManifest.supportedWechatVersions) || + runtimeManifest.supportedWechatVersions.length === 0 + ) { throw new Error('Runtime manifest has no supported WeChat versions') } for (const capability of ['text', 'image', 'voice']) { - if (!Array.isArray(runtimeManifest.capabilities) || !runtimeManifest.capabilities.includes(capability)) { + if ( + !Array.isArray(runtimeManifest.capabilities) || + !runtimeManifest.capabilities.includes(capability) + ) { throw new Error(`Runtime manifest is missing capability: ${capability}`) } } const runtimeBytes = fs.readFileSync(runtimeDylib) for (const key of ['tmSendSourceSha256', 'addressProfileSha256']) { - if (!/^[a-f0-9]{64}$/.test(runtimeManifest[key] || '') || !runtimeBytes.includes(Buffer.from(runtimeManifest[key]))) { + if ( + !/^[a-f0-9]{64}$/.test(runtimeManifest[key] || '') || + !runtimeBytes.includes(Buffer.from(runtimeManifest[key])) + ) { throw new Error(`Runtime dylib does not contain the manifest ${key}`) } } const apiDependencies = run('/usr/bin/otool', ['-L', api]) - if (!apiDependencies.includes('@loader_path/libWCDB.dylib')) throw new Error('WCDB companion dependency missing') + if (!apiDependencies.includes('@loader_path/libWCDB.dylib')) + throw new Error('WCDB companion dependency missing') if (!run('/usr/bin/otool', ['-L', host]).includes('libSystem')) { throw new Error('Host is missing its system runtime dependency') } - if (runtimeDependencies.includes('@rpath/libtmwechat.dylib') && !runtimeDependencies.includes('/usr/lib/libSystem')) { + if ( + runtimeDependencies.includes('@rpath/libtmwechat.dylib') && + !runtimeDependencies.includes('/usr/lib/libSystem') + ) { throw new Error('Runtime dylib is missing required system dependencies') } } function assertStagingTargetDoesNotExist(stageRoot, outputRoot) { for (const target of [stageRoot, outputRoot]) { - if (fs.existsSync(target)) throw new Error(`Refusing to overwrite existing build target: ${target}`) + if (fs.existsSync(target)) + throw new Error(`Refusing to overwrite existing build target: ${target}`) } } @@ -262,26 +328,32 @@ function copyNative(source, destination) { } async function downloadFfmpegArm64(destination) { - const url = 'https://github.com/eugeneware/ffmpeg-static/releases/download/b6.1.1/ffmpeg-darwin-arm64.gz' + const url = + 'https://github.com/eugeneware/ffmpeg-static/releases/download/b6.1.1/ffmpeg-darwin-arm64.gz' const archivePath = `${destination}.gz` await new Promise((resolve, reject) => { - const request = (target) => https.get(target, (response) => { - if (response.statusCode >= 300 && response.statusCode < 400 && response.headers.location) { - response.resume() - request(response.headers.location) - return - } - if (response.statusCode !== 200) { - response.resume() - reject(new Error(`FFmpeg download failed with HTTP ${response.statusCode}`)) - return - } - const output = fs.createWriteStream(archivePath, { flags: 'wx' }) - pipeline(response, output).then(resolve, reject) - }) + const request = (target) => + https.get(target, (response) => { + if (response.statusCode >= 300 && response.statusCode < 400 && response.headers.location) { + response.resume() + request(response.headers.location) + return + } + if (response.statusCode !== 200) { + response.resume() + reject(new Error(`FFmpeg download failed with HTTP ${response.statusCode}`)) + return + } + const output = fs.createWriteStream(archivePath, { flags: 'wx' }) + pipeline(response, output).then(resolve, reject) + }) request(url).on('error', reject) }) - await pipeline(fs.createReadStream(archivePath), createGunzip(), fs.createWriteStream(destination, { flags: 'wx' })) + await pipeline( + fs.createReadStream(archivePath), + createGunzip(), + fs.createWriteStream(destination, { flags: 'wx' }) + ) fs.unlinkSync(archivePath) fs.chmodSync(destination, 0o755) assertArm64(destination, 'Staged FFmpeg') @@ -315,7 +387,8 @@ function assertNoProtectedInputs(root) { } async function prepareEdition(edition) { - if (edition !== 'public' && edition !== 'native') throw new Error('Usage: prepare-macos-edition.cjs ') + if (edition !== 'public' && edition !== 'native') + throw new Error('Usage: prepare-macos-edition.cjs ') const stageRoot = path.join(ROOT, 'build', 'mac-staging', edition) const outputRoot = path.join(ROOT, 'dist', 'mac', edition) assertStagingTargetDoesNotExist(stageRoot, outputRoot) @@ -325,48 +398,69 @@ async function prepareEdition(edition) { fs.mkdirSync(path.dirname(stageRoot), { recursive: true }) fs.mkdirSync(stageRoot) try { - const stagedResources = path.join(stageRoot, 'resources') - fs.mkdirSync(stagedResources, { recursive: true }) - copyPublicResources(sourceResources, stagedResources) - copyFfmpegLicenses(stagedResources) - const ffmpegSha256 = await prepareFfmpeg(stagedResources) + const stagedResources = path.join(stageRoot, 'resources') + fs.mkdirSync(stagedResources, { recursive: true }) + copyPublicResources(sourceResources, stagedResources) + copyFfmpegLicenses(stagedResources) + const ffmpegSha256 = await prepareFfmpeg(stagedResources) - const marker = { profile: edition, appVersion: require(path.join(ROOT, 'package.json')).version, ffmpegSha256 } - if (edition === 'public') { - const api = path.join(WCDB_DIST_ROOT, 'libwcdb_api.dylib') - const companion = path.join(WCDB_DIST_ROOT, 'libWCDB.dylib') - validateWcdbPair(api, companion, 'public') - copyNative(api, path.join(stagedResources, 'wcdb', 'macos', 'arm64', 'libwcdb_api.dylib')) - copyNative(companion, path.join(stagedResources, 'wcdb', 'macos', 'arm64', 'libWCDB.dylib')) - marker.nativeInput = { - source: path.relative(ROOT, WCDB_DIST_ROOT), - libwcdbApiSha256: sha256(api), - libWCDBSha256: sha256(companion) + const marker = { + profile: edition, + appVersion: require(path.join(ROOT, 'package.json')).version, + ffmpegSha256 } - } else { - const { manifest, files } = readAndValidateNativeManifest(NATIVE_BUNDLE_ROOT) - validateNativeBundle(NATIVE_BUNDLE_ROOT, files) - for (const entry of files) { - const remainder = entry.path.replace(/^tracememo\//, '') - const relative = remainder.startsWith('runtime/') - ? path.join(remainder.replace(/^runtime\//, 'runtime/darwin-arm64/')) - : path.join('wcdb', 'macos', 'arm64', remainder.replace(/^wcdb\//, '')) - copyNative(path.join(NATIVE_BUNDLE_ROOT, entry.path), path.join(stagedResources, relative)) + if (edition === 'public') { + const api = path.join(WCDB_DIST_ROOT, 'libwcdb_api.dylib') + const companion = path.join(WCDB_DIST_ROOT, 'libWCDB.dylib') + validateWcdbPair(api, companion, 'public') + copyNative(api, path.join(stagedResources, 'wcdb', 'macos', 'arm64', 'libwcdb_api.dylib')) + copyNative(companion, path.join(stagedResources, 'wcdb', 'macos', 'arm64', 'libWCDB.dylib')) + marker.nativeInput = { + source: path.relative(ROOT, WCDB_DIST_ROOT), + libwcdbApiSha256: sha256(api), + libWCDBSha256: sha256(companion) + } + } else { + const { manifest, files } = readAndValidateNativeManifest(NATIVE_BUNDLE_ROOT) + validateNativeBundle(NATIVE_BUNDLE_ROOT, files) + for (const entry of files) { + const remainder = entry.path.replace(/^tracememo\//, '') + let relative + if (remainder === 'runtime/libtmlicense.dylib') { + // libtmlicense 只给 WCDB helper 用(main 进程的内嵌授权核是静态编译进 + // libtmwechat.dylib 的)。放到 helper 同目录,helper 的 dlopen 候选路径 + // /libtmlicense.dylib 才能命中;放 runtime/ 子目录会让 + // helper 找不到它而 fail-closed。 + relative = path.join('wcdb', 'macos', 'arm64', 'libtmlicense.dylib') + } else if (remainder.startsWith('runtime/')) { + relative = path.join(remainder.replace(/^runtime\//, 'runtime/darwin-arm64/')) + } else { + relative = path.join('wcdb', 'macos', 'arm64', remainder.replace(/^wcdb\//, '')) + } + copyNative(path.join(NATIVE_BUNDLE_ROOT, entry.path), path.join(stagedResources, relative)) + } + marker.nativeInput = { + bundleVersion: manifest.bundleVersion, + manifestSha256: sha256(path.join(NATIVE_BUNDLE_ROOT, 'manifest.json')), + files: files.map(({ path: relative, sha256: digest, bytes }) => ({ + path: relative, + sha256: digest, + bytes + })) + } } - marker.nativeInput = { - bundleVersion: manifest.bundleVersion, - manifestSha256: sha256(path.join(NATIVE_BUNDLE_ROOT, 'manifest.json')), - files: files.map(({ path: relative, sha256: digest, bytes }) => ({ path: relative, sha256: digest, bytes })) - } - } - for (const relative of ['1.txt', 'runtime/runtime.zip']) { - if (fs.existsSync(path.join(stagedResources, relative))) { - throw new Error(`Protected file leaked into ${edition} staging: ${relative}`) + for (const relative of ['1.txt', 'runtime/runtime.zip']) { + if (fs.existsSync(path.join(stagedResources, relative))) { + throw new Error(`Protected file leaked into ${edition} staging: ${relative}`) + } } - } - fs.writeFileSync(path.join(stagedResources, 'tracememo-build.json'), `${JSON.stringify(marker, null, 2)}\n`, { flag: 'wx' }) - console.log(`[prepare-macos-edition] ${edition} resources staged at ${stagedResources}`) + fs.writeFileSync( + path.join(stagedResources, 'tracememo-build.json'), + `${JSON.stringify(marker, null, 2)}\n`, + { flag: 'wx' } + ) + console.log(`[prepare-macos-edition] ${edition} resources staged at ${stagedResources}`) } catch (error) { fs.rmSync(stageRoot, { recursive: true, force: true }) throw error @@ -374,15 +468,20 @@ async function prepareEdition(edition) { } function validateStagedEdition(edition) { - if (edition !== 'public' && edition !== 'native') throw new Error('Usage: validate staged edition ') + if (edition !== 'public' && edition !== 'native') + throw new Error('Usage: validate staged edition ') const resources = path.join(ROOT, 'build', 'mac-staging', edition, 'resources') const markerPath = path.join(resources, 'tracememo-build.json') if (!fs.existsSync(markerPath)) throw new Error(`Missing staged edition marker: ${markerPath}`) const marker = JSON.parse(fs.readFileSync(markerPath, 'utf8')) - if (marker.profile !== edition || marker.appVersion !== require(path.join(ROOT, 'package.json')).version) { + if ( + marker.profile !== edition || + marker.appVersion !== require(path.join(ROOT, 'package.json')).version + ) { throw new Error('Staged edition marker does not match the expected edition/version') } - if (!/^[a-f0-9]{64}$/.test(marker.ffmpegSha256 || '')) throw new Error('Staged FFmpeg hash is invalid') + if (!/^[a-f0-9]{64}$/.test(marker.ffmpegSha256 || '')) + throw new Error('Staged FFmpeg hash is invalid') const ffmpeg = path.join(resources, 'ffmpeg', 'ffmpeg') if (!fs.existsSync(ffmpeg) || sha256(ffmpeg) !== marker.ffmpegSha256) { throw new Error('Staged FFmpeg SHA-256 does not match the edition marker') @@ -399,50 +498,98 @@ function validateStagedEdition(edition) { } if (edition === 'native') { const nativeManifest = marker.nativeInput?.files - if (!Array.isArray(nativeManifest) || nativeManifest.length !== 6) { - throw new Error('Staged native bundle is missing its verified source manifest') + if (!Array.isArray(nativeManifest) || nativeManifest.length !== 7) { + throw new Error( + 'Staged native bundle is missing its verified source manifest (expected seven files)' + ) } for (const item of nativeManifest) { const relative = item.path.replace(/^tracememo\//, '') - const stagedRelative = relative.startsWith('runtime/') - ? relative.replace(/^runtime\//, 'runtime/darwin-arm64/') - : path.join('wcdb', 'macos', 'arm64', relative.replace(/^wcdb\//, '')) + let stagedRelative + if (relative === 'runtime/libtmlicense.dylib') { + stagedRelative = path.join('wcdb', 'macos', 'arm64', 'libtmlicense.dylib') + } else if (relative.startsWith('runtime/')) { + stagedRelative = relative.replace(/^runtime\//, 'runtime/darwin-arm64/') + } else { + stagedRelative = path.join('wcdb', 'macos', 'arm64', relative.replace(/^wcdb\//, '')) + } const staged = path.join(resources, stagedRelative) - if (!fs.existsSync(staged) || fs.statSync(staged).size !== item.bytes || sha256(staged) !== item.sha256) { + if ( + !fs.existsSync(staged) || + fs.statSync(staged).size !== item.bytes || + sha256(staged) !== item.sha256 + ) { throw new Error(`Staged native artifact hash mismatch: ${item.path}`) } } - validateNativeBundleFromStaging(resources) + validateNativeBundleFromStaging(resources) } for (const relative of ['1.txt', 'runtime/runtime.zip']) { - if (fs.existsSync(path.join(resources, relative))) throw new Error(`Protected file leaked into staging: ${relative}`) + if (fs.existsSync(path.join(resources, relative))) + throw new Error(`Protected file leaked into staging: ${relative}`) + } + return { + edition, + appVersion: marker.appVersion, + apiSha256: sha256(api), + companionSha256: sha256(companion), + ffmpegSha256: sha256(ffmpeg) } - return { edition, appVersion: marker.appVersion, apiSha256: sha256(api), companionSha256: sha256(companion), ffmpegSha256: sha256(ffmpeg) } } function validateNativeBundleFromStaging(resources) { const api = path.join(resources, 'wcdb', 'macos', 'arm64', 'libwcdb_api.dylib') const companion = path.join(resources, 'wcdb', 'macos', 'arm64', 'libWCDB.dylib') const helper = path.join(resources, 'wcdb', 'macos', 'arm64', 'tm-wcdb-config-helper') + const licenseDylib = path.join(resources, 'wcdb', 'macos', 'arm64', 'libtmlicense.dylib') const host = path.join(resources, 'runtime', 'darwin-arm64', 'tm-wechat-host') const runtimeDylib = path.join(resources, 'runtime', 'darwin-arm64', 'libtmwechat.dylib') - const runtimeManifestPath = path.join(resources, 'runtime', 'darwin-arm64', 'runtime-manifest.json') + const runtimeManifestPath = path.join( + resources, + 'runtime', + 'darwin-arm64', + 'runtime-manifest.json' + ) + if (!fs.existsSync(licenseDylib)) { + throw new Error('Staged native edition is missing libtmlicense.dylib next to the WCDB helper') + } const symbols = exportedSymbols(api) const missing = REQUIRED_NATIVE_SYMBOLS.filter((symbol) => !symbols.includes(symbol)) if (missing.length) throw new Error(`Staged native WCDB ABI is missing: ${missing.join(', ')}`) - for (const [binary, label] of [[companion, 'WCDB companion'], [helper, 'WCDB helper'], [host, 'Host'], [runtimeDylib, 'Runtime dylib']]) { + for (const [binary, label] of [ + [companion, 'WCDB companion'], + [helper, 'WCDB helper'], + [licenseDylib, 'License core'], + [host, 'Host'], + [runtimeDylib, 'Runtime dylib'] + ]) { assertArm64(binary, label) } + // helper must be able to dlopen libtmlicense.dylib: it must sit in the same directory. + const licenseSignature = run('/usr/bin/codesign', ['--verify', '--strict', licenseDylib]) + if (licenseSignature.trim() !== '') { + throw new Error( + `Staged libtmlicense.dylib code signature is invalid: ${licenseSignature.trim()}` + ) + } if (!run('/usr/bin/otool', ['-L', helper]).includes('@loader_path/libwcdb_api.dylib')) { throw new Error('Staged helper lost its @loader_path WCDB dependency') } const runtimeManifest = JSON.parse(fs.readFileSync(runtimeManifestPath, 'utf8')) const runtimeBytes = fs.readFileSync(runtimeDylib) - if (runtimeManifest.runtime !== 'tm-wechat-native' || runtimeManifest.platform !== 'darwin-arm64' || runtimeManifest.architecture !== 'arm64' || runtimeManifest.protocolVersion !== 1) { + if ( + runtimeManifest.runtime !== 'tm-wechat-native' || + runtimeManifest.platform !== 'darwin-arm64' || + runtimeManifest.architecture !== 'arm64' || + runtimeManifest.protocolVersion !== 1 + ) { throw new Error('Staged Runtime Manifest identity is invalid') } for (const key of ['tmSendSourceSha256', 'addressProfileSha256']) { - if (!/^[a-f0-9]{64}$/.test(runtimeManifest[key] || '') || !runtimeBytes.includes(Buffer.from(runtimeManifest[key]))) { + if ( + !/^[a-f0-9]{64}$/.test(runtimeManifest[key] || '') || + !runtimeBytes.includes(Buffer.from(runtimeManifest[key])) + ) { throw new Error(`Staged runtime hash verification failed: ${key}`) } } @@ -450,10 +597,10 @@ function validateNativeBundleFromStaging(resources) { if (require.main === module) { try { - prepareEdition(process.argv[2]).catch((error) => { - console.error(error instanceof Error ? error.message : String(error)) - process.exitCode = 1 - }) + prepareEdition(process.argv[2]).catch((error) => { + console.error(error instanceof Error ? error.message : String(error)) + process.exitCode = 1 + }) } catch (error) { console.error(error instanceof Error ? error.message : String(error)) process.exitCode = 1 diff --git a/src/main/index.ts b/src/main/index.ts index e48ce98..ae9a9b3 100644 --- a/src/main/index.ts +++ b/src/main/index.ts @@ -1557,15 +1557,16 @@ app.whenReady().then(async () => { /** * 正式 MessageListener(Observation Mode 接入)。 * - * 本轮**只监听、回读、规范化、去重、统计**,不触发任何业务: + * 只监听、回读、规范化、去重、统计,不触发任何业务: * 不匹配关键词、不判断 @我、不出日报、不回复、不调 AI / Agent、不发送。 - * 下一层的 Trigger 由后续任务接入。 + * 业务响应由上层消费者自行订阅,不在监听层实现。 */ const messageListener = new MessageListenerService(wcdb4Client) /** * Automation v1(@我生成日报)。 * - * `isListening` 要等下面 `startMonitor` 有结果才知道,所以先用闭包变量占位。 + * `isListening` 反映 `startMonitor` 的实际结果,因此通过闭包读取, + * 而不是在初始化时传入快照。 */ let automationListening = false initAutomationService(wcdb4Client, { isListening: () => automationListening }) @@ -3442,6 +3443,15 @@ app.whenReady().then(async () => { return { success: true } }) ipcMain.handle('wechat-personal:getStatus', () => currentPersonalWechatSenderStatus()) + ipcMain.handle('wechat-personal:getMacLicenseStatus', () => + macWechatRuntimeManager.getMacLicenseStatus() + ) + ipcMain.handle('wechat-personal:getMacSendRuntimeAvailability', () => + macWechatRuntimeManager.getSendRuntimeAvailability() + ) + ipcMain.handle('wechat-personal:refreshMacLicense', () => + macWechatRuntimeManager.refreshMacLicense() + ) ipcMain.handle('wechat-personal:checkStatus', (_, port?: string) => personalWechatSendService.checkWindowsStatus(port) ) diff --git a/src/main/services/mac-wechat-runtime-manager.ts b/src/main/services/mac-wechat-runtime-manager.ts index 0ac3048..70fc808 100644 --- a/src/main/services/mac-wechat-runtime-manager.ts +++ b/src/main/services/mac-wechat-runtime-manager.ts @@ -1,20 +1,30 @@ import { spawn, type ChildProcess } from 'child_process' import { chmodSync, existsSync } from 'fs' -import { get } from 'http' +import { get, request as httpRequest } from 'http' import { join } from 'path' import { app } from 'electron' import { appLogger } from '../app-logger' -import { isMacNativeRuntimeUnavailable, resolveWechatRuntimeDirectory } from '../native-runtime-paths' +import { + isMacNativeRuntimeUnavailable, + resolveWechatRuntimeDirectory +} from '../native-runtime-paths' +import type { MacLicenseStatus } from '../../shared/personal-wechat-mac-license' +import { + offlineMacLicenseStatus, + parseMacLicenseStatus +} from '../../shared/personal-wechat-mac-license' import type { MacWechatBindResult, MacWechatBindingStatus, MacWechatRuntimeManifest, MacWechatRuntimeLifecycle, - MacWechatRuntimeSnapshot + MacWechatRuntimeSnapshot, + MacWechatSendRuntimeAvailabilityResult } from '../../shared/personal-wechat-mac-runtime' import type { PersonalWechatSenderStatus } from '../../shared/personal-wechat' +import { hasValidWechatLicense } from '../../shared/personal-wechat-mac-send-action' import { bindingMatchesRuntimeManifest, readMacWechatRuntimeManifest @@ -43,6 +53,10 @@ const HOST = '127.0.0.1' const START_TIMEOUT_MS = 15_000 const REQUEST_TIMEOUT_MS = 30_000 const CRASH_RESTART_DELAY_MS = 1_500 +/* /license/status is a local cache read; keep it snappy. /license/refresh runs a + * real challenge->sign->check cycle inside the host, which is bounded at 15s. */ +const LICENSE_STATUS_TIMEOUT_MS = 8_000 +const LICENSE_REFRESH_TIMEOUT_MS = 20_000 interface MacWechatSenderStatusInput { snapshot: MacWechatRuntimeSnapshot @@ -119,12 +133,9 @@ export function deriveMacWechatSenderStatus({ identityMatches && state === 'online' && (binding?.sendContextReady === true || nativeBindingReady) - const canSendText = - bindingReady && supportsCapability('text') && binding?.canSendText === true - const canSendImage = - bindingReady && supportsCapability('image') && binding?.canSendImage === true - const canSendVoice = - bindingReady && supportsCapability('voice') && binding?.canSendVoice === true + const canSendText = bindingReady && supportsCapability('text') && binding?.canSendText === true + const canSendImage = bindingReady && supportsCapability('image') && binding?.canSendImage === true + const canSendVoice = bindingReady && supportsCapability('voice') && binding?.canSendVoice === true const sessionAttached = identityMatches && (binding?.sessionAttached ?? false) const scriptLoaded = identityMatches && (binding?.scriptLoaded ?? false) @@ -157,6 +168,25 @@ export function deriveMacWechatSenderStatus({ } } +/** + * 在线刷新失败时的返回策略: + * 缓存里还有可用授权就保留它(只把失败写进 message),否则明确报告网络故障。 + * 单独抽出来是因为这两条分支都必须可测 —— 把网络故障错报成「已撤销」会让 + * 用户去找客服,错报成「有效」又会掩盖真实故障。 + */ +export function resolveLicenseRefreshFailure( + snapshot: MacLicenseStatus | null, + diagnostic: string +): MacLicenseStatus { + if (snapshot?.authorized) { + return { + ...snapshot, + message: `本次刷新失败:${diagnostic}(仍使用本地缓存授权)` + } + } + return offlineMacLicenseStatus('server_unavailable', diagnostic) +} + class MacWechatRuntimeManager { private child: ChildProcess | null = null private lifecycle: MacWechatRuntimeLifecycle = 'stopped' @@ -211,6 +241,21 @@ class MacWechatRuntimeManager { } } + getSendRuntimeAvailability(): MacWechatSendRuntimeAvailabilityResult { + if (isMacNativeRuntimeUnavailable()) { + return { state: 'unavailable', message: '当前版本没有微信发送能力' } + } + try { + const runtimeDir = this.resolveRuntimeDir() + if (!runtimeDir) throw new Error('发送 Runtime 目录缺失') + this.manifest = readMacWechatRuntimeManifest(runtimeDir) + return { state: 'available', message: '微信发送组件可用' } + } catch (error) { + const detail = error instanceof Error ? error.message : String(error) + return { state: 'component_error', message: `发送组件缺失或异常:${detail}` } + } + } + /** * Start the host if it is not already running. Deliberately lazy: the host * comes up WITHOUT touching WeChat (lazy init inside the host), so "runtime @@ -423,11 +468,28 @@ class MacWechatRuntimeManager { private request( method: string, path: string, - timeoutMs = REQUEST_TIMEOUT_MS + timeoutMs = REQUEST_TIMEOUT_MS, + body?: string ): Promise<{ status: number | null; body: string }> { return new Promise((resolve) => { - const request = get( - { host: HOST, port: PORT, path, method, timeout: timeoutMs }, + const payload = body !== undefined ? Buffer.from(body, 'utf8') : undefined + // GET keeps using `get()` (auto-end); POST goes through `request()` so we + // can attach a JSON body. Both funnel into the same resolve contract. + const transport = method === 'GET' || method === 'HEAD' ? get : httpRequest + const req = transport( + { + host: HOST, + port: PORT, + path, + method, + timeout: timeoutMs, + headers: payload + ? { + 'Content-Type': 'application/json', + 'Content-Length': payload.length + } + : undefined + }, (response) => { let body = '' response.on('data', (chunk) => { @@ -438,14 +500,15 @@ class MacWechatRuntimeManager { }) } ) - request.on('timeout', () => { - request.destroy() + req.on('timeout', () => { + req.destroy() resolve({ status: null, body: '' }) }) - request.on('error', () => { + req.on('error', () => { resolve({ status: null, body: '' }) }) - request.end() + if (payload) req.write(payload) + req.end() }) } @@ -527,6 +590,97 @@ class MacWechatRuntimeManager { return this.lastBinding } + // GET reads the local snapshot; POST runs one real online check. + // Neither touches the WeChat binding. + + /** Local snapshot. Never attaches to WeChat, never forces a network refresh. + * 404 means the host predates these endpoints — not "unlicensed". */ + async getMacLicenseStatus(): Promise { + const availability = this.getSendRuntimeAvailability() + if (availability.state === 'unavailable') { + return offlineMacLicenseStatus('platform_unsupported', '当前构建不包含 Mac 发送能力') + } + if (availability.state !== 'available') { + return offlineMacLicenseStatus('runtime_missing', availability.message) + } + if (this.lifecycle === 'stopped') await this.ensureStarted() + const { status, body } = await this.request('GET', '/license/status', LICENSE_STATUS_TIMEOUT_MS) + if (status === null) { + return offlineMacLicenseStatus('runtime_missing', 'Mac 发送组件未运行,请先启动发送组件') + } + if (status === 404) { + return offlineMacLicenseStatus( + 'unsupported', + '当前发送组件版本较旧,不支持授权检测。请升级或重启发送组件后再试。' + ) + } + if (status !== 200) { + return offlineMacLicenseStatus('runtime_missing', `授权状态查询失败(HTTP ${status})`) + } + try { + return parseMacLicenseStatus(JSON.parse(body)) + } catch { + return offlineMacLicenseStatus('runtime_missing', '授权状态响应无法解析') + } + } + + /** + * One real online check; re-entrant calls return the current snapshot instead + * of minting a duplicate challenge. Network failure maps to server_unavailable, + * never to revoked. + */ + async refreshMacLicense(): Promise { + const availability = this.getSendRuntimeAvailability() + if (availability.state === 'unavailable') { + return offlineMacLicenseStatus('platform_unsupported', '当前构建不包含 Mac 发送能力') + } + if (availability.state !== 'available') { + return offlineMacLicenseStatus('runtime_missing', availability.message) + } + if (this.lifecycle === 'stopped') await this.ensureStarted() + if (this.licenseRefreshInFlight) { + // A refresh is already running; answer from the local snapshot so the + // button click is a no-op instead of stacking a second online check. + return this.getMacLicenseStatus() + } + this.licenseRefreshInFlight = true + try { + const { status, body } = await this.request( + 'POST', + '/license/refresh', + LICENSE_REFRESH_TIMEOUT_MS, + '{}' + ) + if (status === null) { + const snapshot = await this.getMacLicenseStatus().catch(() => null) + return resolveLicenseRefreshFailure(snapshot, '无法连接授权服务器,请检查网络后重试') + } + if (status === 404) { + return offlineMacLicenseStatus( + 'unsupported', + '当前发送组件版本较旧,不支持授权检测。请升级或重启发送组件后再试。' + ) + } + let envelope: Record + try { + envelope = JSON.parse(body) as Record + } catch { + return offlineMacLicenseStatus('runtime_missing', '授权刷新响应无法解析') + } + // The host wraps the result: { ok, code, message, status: MacLicenseStatus } + const nested = envelope.status ?? envelope + const parsed = parseMacLicenseStatus(nested) + if (typeof envelope.errorCode === 'number' && parsed.errorCode == null) { + parsed.errorCode = envelope.errorCode + } + return parsed + } finally { + this.licenseRefreshInFlight = false + } + } + + private licenseRefreshInFlight = false + /* * Build the legacy PersonalWechatSenderStatus contract from the live mac * runtime state. Lives here (not in the capability service) so BOTH the @@ -650,7 +804,8 @@ class MacWechatRuntimeManager { * live WeChat pid again returns attached=false and never double-attaches. */ async bind(): Promise { - if (isMacNativeRuntimeUnavailable()) { + const availability = this.getSendRuntimeAvailability() + if (availability.state === 'unavailable') { return { ok: false, attached: false, @@ -658,6 +813,9 @@ class MacWechatRuntimeManager { message: '当前环境不包含微信发送能力' } } + if (availability.state !== 'available') { + return { ok: false, attached: false, state: 'runtime_offline', message: availability.message } + } if (this.lifecycle !== 'online') { const snapshot = await this.ensureStarted() if (snapshot.lifecycle !== 'online') { @@ -684,6 +842,28 @@ class MacWechatRuntimeManager { } } + const license = await this.getMacLicenseStatus() + const licenseAllowed = hasValidWechatLicense(license) + if (!licenseAllowed) { + const tokenExpiresAt = license.tokenExpiresAt + ? Date.parse(license.tokenExpiresAt) + : Number.NaN + const message = + license.state === 'revoked' + ? 'LICENSE_REVOKED: 微信发送授权已撤销' + : license.state === 'expired' || + (Number.isFinite(tokenExpiresAt) && tokenExpiresAt <= Date.now()) + ? 'LICENSE_EXPIRED: 微信发送授权已过期' + : license.state === 'device_mismatch' + ? 'LICENSE_DEVICE_MISMATCH: 授权与当前设备不匹配' + : license.state === 'identity_error' + ? 'LICENSE_IDENTITY_ERROR: 设备身份异常' + : license.authorized && !license.features.includes('wechat') + ? 'LICENSE_FEATURE_DENIED: 未开通微信发送' + : 'LICENSE_REQUIRED: 需要有效的微信发送授权' + return { ok: false, attached: false, state: 'host_error', message } + } + const { status, body } = await this.request('POST', '/bindWeChat') await this.refreshBinding().catch(() => null) diff --git a/src/preload/index.d.ts b/src/preload/index.d.ts index d161648..05001a1 100644 --- a/src/preload/index.d.ts +++ b/src/preload/index.d.ts @@ -84,6 +84,8 @@ import type { PersonalWechatVoiceDiagnostic } from '../shared/personal-wechat' import type { PersonalWechatSendCapability } from '../shared/personal-wechat' +import type { MacLicenseStatus } from '../shared/personal-wechat-mac-license' +import type { MacWechatSendRuntimeAvailabilityResult } from '../shared/personal-wechat-mac-runtime' import type { GroupMemberStatsQuery, GroupMemberStatsResult } from '../shared/group-stats' import type { ScheduledReportExecution, @@ -751,6 +753,9 @@ declare global { repairImageTextIndex: () => Promise onImageTextIndexStatus: (callback: (status: ImageTextIndexStatus) => void) => () => void getPersonalWechatSenderStatus: () => Promise + getMacLicenseStatus: () => Promise + getMacSendRuntimeAvailability: () => Promise + refreshMacLicense: () => Promise getPersonalWechatSendCapability: () => Promise checkPersonalWechatSenderStatus: (port?: string) => Promise checkPersonalWechatVoiceEncodingEnvironment: () => Promise diff --git a/src/preload/index.ts b/src/preload/index.ts index 9a7b3e1..8a29c52 100644 --- a/src/preload/index.ts +++ b/src/preload/index.ts @@ -14,6 +14,8 @@ import type { SaveGeneratedReportRequest, UpdateGeneratedReportTemplateRequest } from '../shared/report-history' +import type { MacLicenseStatus } from '../shared/personal-wechat-mac-license' +import type { MacWechatSendRuntimeAvailabilityResult } from '../shared/personal-wechat-mac-runtime' import type { AIChatRequestOptions, AiSearchExternalAuthorizationRequest, @@ -585,6 +587,12 @@ const api = { }, getPersonalWechatSenderStatus: (): Promise => ipcRenderer.invoke('wechat-personal:getStatus'), + getMacLicenseStatus: (): Promise => + ipcRenderer.invoke('wechat-personal:getMacLicenseStatus'), + getMacSendRuntimeAvailability: (): Promise => + ipcRenderer.invoke('wechat-personal:getMacSendRuntimeAvailability'), + refreshMacLicense: (): Promise => + ipcRenderer.invoke('wechat-personal:refreshMacLicense'), getPersonalWechatSendCapability: (): Promise => ipcRenderer.invoke('wechat-personal:getSendCapability'), checkPersonalWechatSenderStatus: (port?: string): Promise => diff --git a/src/renderer/src/components/chat/PersonalWechatSetupGuide.tsx b/src/renderer/src/components/chat/PersonalWechatSetupGuide.tsx index ad268e8..24e4c14 100644 --- a/src/renderer/src/components/chat/PersonalWechatSetupGuide.tsx +++ b/src/renderer/src/components/chat/PersonalWechatSetupGuide.tsx @@ -8,19 +8,20 @@ interface PersonalWechatSetupGuideProps { binding: boolean detecting: boolean sessionBound: boolean - onBind: () => void - onStartSending: () => void + onBind?: () => void + onStartSending?: () => void onOpenTextToSpeechSettings?: () => void -} - -function capabilityLabel(ready: boolean, initializing: boolean): string { - if (ready) return '已就绪' - return initializing ? '初始化中' : '未就绪' + showBindAction?: boolean + showStartSendingAction?: boolean + showCapabilityStatus?: boolean + showBindingInstructionsInInitialization?: boolean + showAuthorizationWarning?: boolean + canBind?: boolean } function bindingHint(status: PersonalWechatSenderStatus): string { if (status.state === 'wechat_not_running') { - return '请保持微信未登录窗口状态,点击“绑定微信”后,再点击微信窗口登录。' + return '4.1.13以下请保持微信未登录窗口状态,点击“绑定微信”后,再点击微信窗口登录。4.1.13以上登录状态微信直接点击“绑定微信”' } if (status.state === 'unsupported_platform') return '当前系统暂不支持个人微信发送。' if (status.state === 'unsupported_version') @@ -29,7 +30,7 @@ function bindingHint(status: PersonalWechatSenderStatus): string { return '请先完成发送运行时准备。' } if (status.state === 'error') return '连接微信时遇到问题,请稍后重试。' - return '请保持微信未登录窗口状态,点击“绑定微信”后,再点击微信窗口登录。' + return '4.1.13以下请保持微信未登录窗口状态,点击“绑定微信”后,再点击微信窗口登录。4.1.13以上登录状态微信直接点击“绑定微信”' } function isWechatBound(status: PersonalWechatSenderStatus): boolean { @@ -41,6 +42,11 @@ function isWechatBound(status: PersonalWechatSenderStatus): boolean { ) } +function capabilityLabel(ready: boolean, initializing: boolean): string { + if (ready) return '已就绪' + return initializing ? '初始化中' : '未就绪' +} + export function PersonalWechatSetupGuide({ senderStatus, binding, @@ -48,7 +54,13 @@ export function PersonalWechatSetupGuide({ sessionBound, onBind, onStartSending, - onOpenTextToSpeechSettings + onOpenTextToSpeechSettings, + showBindAction = true, + showStartSendingAction = true, + showCapabilityStatus = true, + showBindingInstructionsInInitialization = false, + showAuthorizationWarning = true, + canBind = true }: PersonalWechatSetupGuideProps): React.ReactElement { const runtimeUnavailable = senderStatus?.state === 'runtime_missing' const runtimeLabel = '发送运行时' @@ -76,7 +88,7 @@ export function PersonalWechatSetupGuide({ 准备 {runtimeLabel}

{runtimeUnavailable - ? `个人微信发送需要${runtimeLabel},授权后即可使用。` + ? '当前版本没有微信发送能力。' : `${runtimeLabel}随 TraceMemo 一起提供,无需额外安装。`}

{runtimeReady ? ( @@ -89,65 +101,79 @@ export function PersonalWechatSetupGuide({ -
  • - {connected ? '✓' : '2'} -
    - 绑定个人微信 -

    请保持微信未登录窗口状态,点击“绑定微信”后,再点击微信窗口登录。

    - {connected ? ( - ✓ 微信已绑定 - ) : ( - - )} - {!connected && senderStatus && !runtimeUnavailable && ( -

    {bindingHint(senderStatus)}

    - )} - {!connected && runtimeUnavailable && ( -
    - ! -

    - 发送能力属授权制,需要联系群主。请先加入交流群,然后在群内添加群主申请授权。 - 进群请点击{' '} - - 这里 - {' '} - 跳转。 -

    -
    - )} - {!connected && !runtimeUnavailable && ( -

    - 绑定微信可能导致当前微信异常闪退,这是正常现象。若微信退出,请重新启动微信后,再回到这里重新检测/绑定。 + {showBindAction ? ( +

  • + {connected ? '✓' : '2'} +
    + 绑定个人微信 +

    + 4.1.13以下请保持微信未登录窗口状态,点击“绑定微信”后,再点击微信窗口登录。
    - 微信总是自动更新?请在微信左下角打开“设置 → - 通用”,取消勾选“有更新时自动升级微信”,否则版本变化后可能无法绑定。 + 4.1.13以上登录状态微信直接点击“绑定微信”

    - )} -
    -
  • + {connected ? ( + ✓ 微信已绑定 + ) : ( + + )} + {!connected && senderStatus && !runtimeUnavailable ? ( +

    {bindingHint(senderStatus)}

    + ) : null} + {!connected && runtimeUnavailable && showAuthorizationWarning ? ( +
    + ! +

    + 发送能力属授权制,需要联系群主。请先加入交流群,然后在群内添加群主申请授权。 + 进群请点击{' '} + + 这里 + {' '} + 跳转。 +

    +
    + ) : null} + {!connected && !runtimeUnavailable ? ( +

    + 绑定微信可能导致当前微信异常闪退,这是正常现象。若微信退出,请重新启动微信后,再回到这里重新检测/绑定。 +
    + 微信总是自动更新?请在微信左下角打开“设置 → + 通用”,取消勾选“有更新时自动升级微信”,否则版本变化后可能无法绑定。 +

    + ) : null} + + + ) : null}
  • - {allReady ? '✓' : '3'} + + {allReady ? '✓' : showBindAction ? '3' : '2'} +
    初始化发送能力 -

    绑定微信后,TraceMemo 会自动完成文字、图片和语音发送所需的初始化。

    +

    每个微信进程只能绑定一次

    + {showBindingInstructionsInInitialization && ( + <> +

    4.1.13以下请保持微信未登录窗口状态,点击“绑定微信”后,再点击微信窗口登录。

    +

    4.1.13以上登录状态微信直接点击“绑定微信”

    + + )} {initializing && (

    {detecting ? '正在初始化发送能力…' : '正在等待发送运行时完成初始化…'} @@ -161,37 +187,43 @@ export function PersonalWechatSetupGuide({

  • -
  • - {allReady ? '✓' : '4'} -
    - 能力检测 -
    - {[ - ['文字消息', Boolean(senderStatus?.canSendText)], - ['图片消息', Boolean(senderStatus?.canSendImage)], - ['语音消息', canSendVoice] - ].map(([label, ready]) => ( - - {ready ? '✓' : '−'} - {label} - {capabilityLabel(Boolean(ready), initializing)} - - ))} + {showCapabilityStatus ? ( +
  • + + {allReady ? '✓' : showBindAction ? '4' : '3'} + +
    + 能力检测 +
    + {[ + ['文字消息', Boolean(senderStatus?.canSendText)], + ['图片消息', Boolean(senderStatus?.canSendImage)], + ['语音消息', canSendVoice] + ].map(([label, ready]) => ( + + {ready ? '✓' : '−'} + {label} + {capabilityLabel(Boolean(ready), initializing)} + + ))} +
    + {allReady ? ( + <> + 微信消息发送已配置完成 + {showStartSendingAction && ( + + )} + + ) : initializing ? ( +

    + 发送能力准备完成后会自动进入已就绪状态。 +

    + ) : null}
    - {allReady ? ( - <> - 微信消息发送已配置完成 - - - ) : initializing ? ( -

    - 发送能力准备完成后会自动进入已就绪状态。 -

    - ) : null} - -
  • + + ) : null} {!runtimeReady && runtimeUnavailable && onOpenTextToSpeechSettings && ( diff --git a/src/renderer/src/features/settings/pages/PersonalWechatSendPage.tsx b/src/renderer/src/features/settings/pages/PersonalWechatSendPage.tsx index b05abe6..57c5a64 100644 --- a/src/renderer/src/features/settings/pages/PersonalWechatSendPage.tsx +++ b/src/renderer/src/features/settings/pages/PersonalWechatSendPage.tsx @@ -1,8 +1,14 @@ -import { useCallback, useEffect, useState, type ReactElement } from 'react' +import { useCallback, useEffect, useRef, useState, type ReactElement } from 'react' import type { PersonalWechatSendCapability, PersonalWechatSenderStatus } from '../../../../../shared/personal-wechat' +import type { + MacLicenseState, + MacLicenseStatus +} from '../../../../../shared/personal-wechat-mac-license' +import type { MacWechatSendRuntimeAvailabilityResult } from '../../../../../shared/personal-wechat-mac-runtime' +import { resolveMacSendPrimaryAction } from '../../../../../shared/personal-wechat-mac-send-action' import { Button, Input, Skeleton } from '../../../components/ui' import { PersonalWechatSetupGuide } from '../../../components/chat/PersonalWechatSetupGuide' import { isMac, isWindows } from '../../../utils/runtime-environment' @@ -60,6 +66,190 @@ function SendCapabilityAuthorizationCard(): ReactElement { ) } +const macLicenseStateLabel: Record = { + unlicensed: '当前设备暂无发送能力授权', + valid: '已授权', + cached: '授权有效(本地缓存)', + expired: '授权已过期', + revoked: '授权已撤销', + device_mismatch: '授权与当前设备不匹配', + identity_error: '设备身份异常', + server_unavailable: '授权服务器不可用', + checking: '检测中…', + unsupported: '发送组件版本较旧', + runtime_missing: '发送组件未运行', + platform_unsupported: '当前构建不支持' +} + +const macLicenseFeatureLabel: Record = { + basic: '基础功能', + wechat: '微信发送', + advanced: '高级功能', + api: 'API 接口' +} + +function licenseTone(state: MacLicenseState): string { + if (state === 'valid' || state === 'cached') return 'is-ready' + if (state === 'revoked' || state === 'expired' || state === 'identity_error') return 'is-error' + return 'is-neutral' +} + +function formatMacLicenseDateTime(iso: string | null): string { + if (!iso) return '—' + const parsed = new Date(iso) + if (Number.isNaN(parsed.getTime())) return iso + return parsed.toLocaleString('zh-CN', { + year: 'numeric', + month: '2-digit', + day: '2-digit', + hour: '2-digit', + minute: '2-digit' + }) +} + +function formatMacLicenseDate(iso: string | null): string { + if (!iso) return '—' + const parsed = new Date(iso) + if (Number.isNaN(parsed.getTime())) return iso + return parsed.toLocaleDateString('zh-CN', { + year: 'numeric', + month: '2-digit', + day: '2-digit' + }) +} + +function summarizeDeviceId(deviceId: string): string { + return deviceId.length === 68 ? `${deviceId.slice(0, 12)}…${deviceId.slice(-6)}` : deviceId +} + +/** 展示当前设备的授权状态,并提供刷新与复制设备 ID 的操作。 */ +export function MacProLicenseCard({ + onNotice, + onStatusChange +}: { + onNotice: (message: string) => void + onStatusChange: (status: MacLicenseStatus) => void +}): ReactElement { + const [license, setLicense] = useState(null) + const [refreshing, setRefreshing] = useState(false) + const [copied, setCopied] = useState(false) + + const load = useCallback(async (): Promise => { + try { + const next = await window.api.getMacLicenseStatus() + setLicense(next) + onStatusChange(next) + } catch { + setLicense(null) + } + }, [onStatusChange]) + + useEffect(() => { + void load() + }, [load]) + + const refresh = async (): Promise => { + if (refreshing) return + setRefreshing(true) + try { + const next = await window.api.refreshMacLicense() + setLicense(next) + onStatusChange(next) + if (next.authorized) { + onNotice('授权检测完成:已授权') + } else { + onNotice(next.message || '授权检测完成') + } + } catch (reason) { + onNotice(reason instanceof Error ? reason.message : '授权检测失败') + } finally { + setRefreshing(false) + } + } + + const copyDeviceId = async (): Promise => { + if (!license?.deviceId) return + try { + await navigator.clipboard.writeText(license.deviceId) + setCopied(true) + onNotice('设备 ID 已复制') + window.setTimeout(() => setCopied(false), 2_000) + } catch { + onNotice('复制失败,请手动选择设备 ID 复制') + } + } + + if (!license) { + return + } + // OSS 构建走到这里(platform_unsupported)时不渲染卡片,保证免费版不出现授权入口。 + if (license.state === 'platform_unsupported') { + return <> + } + + return ( +
    +
    + 发送能力授权 + + {license.state === 'valid' || license.state === 'cached' + ? '设备已授权' + : macLicenseStateLabel[license.state]} + +
    + +
    +
    + 本机设备 ID + + {license.deviceId ? summarizeDeviceId(license.deviceId) : '(尚未生成)'} + +
    + +
    + {license.deviceId && !license.authorized ? ( +

    + 将设备 ID 提供给授权管理员,完成授权后点击「重新检测授权」。 +

    + ) : null} + {license.authorized && license.features.length > 0 ? ( +
    + {license.features.map((feature) => ( + {macLicenseFeatureLabel[feature] || feature} + ))} +
    + ) : null} +
    + + 授权到期 {formatMacLicenseDate(license.licenseExpiresAt)} + + + 最近检测 {formatMacLicenseDateTime(license.lastCheckedAt)} + +
    +
    + + +
    +
    + ) +} + export function PersonalWechatSendPage({ onNotice, onOpenTextToSpeechSettings @@ -79,6 +269,11 @@ export function PersonalWechatSendPage({ const [windowsPortInput, setWindowsPortInput] = useState('') const [windowsDetectedPort, setWindowsDetectedPort] = useState('') const [windowsEndpointBusy, setWindowsEndpointBusy] = useState(false) + const [setupExpanded, setSetupExpanded] = useState(null) + const [macLicenseStatus, setMacLicenseStatus] = useState(null) + const [macRuntimeAvailability, setMacRuntimeAvailability] = + useState(null) + const setupDefaultInitialized = useRef(false) const refresh = useCallback(async (): Promise => { if (isWindows) { setLoading(false) @@ -101,7 +296,59 @@ export function PersonalWechatSendPage({ useEffect(() => { if (isWindows) return - void refresh() + let active = true + const loadMacStatus = async (): Promise => { + try { + const availability = await window.api.getMacSendRuntimeAvailability() + if (!active) return + setMacRuntimeAvailability(availability) + if (availability.state !== 'available') { + setSenderStatus({ + state: 'runtime_missing', + platform: 'darwin', + arch: 'arm64', + sipDisabled: true, + wechatRunning: false, + endpoint: '', + endpointReady: false, + runtimeReady: false, + attachReady: false, + baseAddressReady: false, + textHookInstalled: false, + textHookReady: false, + imageHookInstalled: false, + imageHookReady: false, + messageListenerReady: false, + canSend: false, + canSendText: false, + canSendImage: false, + canSendVoice: false, + message: availability.message, + error: availability.message + }) + setLoading(false) + return + } + const [nextCapability, nextSender, license] = await Promise.all([ + window.api.getPersonalWechatSendCapability(), + window.api.getPersonalWechatSenderStatus(), + window.api.getMacLicenseStatus() + ]) + if (!active) return + setCapability(nextCapability) + setSenderStatus(nextSender) + setMacLicenseStatus(license) + } catch (reason) { + if (!active) return + setError(reason instanceof Error ? reason.message : '微信发送能力读取失败') + } finally { + if (active) setLoading(false) + } + } + void loadMacStatus() + return () => { + active = false + } }, [refresh]) useEffect(() => { @@ -266,7 +513,27 @@ export function PersonalWechatSendPage({ const pageMessage = isWindows ? windowsSenderStatus?.message || '请输入端口并检测 Windows 微信发送能力' : capability?.message || '微信发送能力暂不可用' - const macUnavailable = isMac && senderStatus?.state === 'runtime_missing' + const macUnavailable = isMac && macRuntimeAvailability?.state === 'unavailable' + const macComponentError = isMac && macRuntimeAvailability?.state === 'component_error' + const macBound = boundToCurrentWechat(senderStatus) + const macEnvironmentReady = Boolean( + senderStatus?.runtimeReady && macBound && senderStatus.canSend + ) + useEffect(() => { + if (isMac && senderStatus && !setupDefaultInitialized.current) { + setSetupExpanded(!macEnvironmentReady) + setupDefaultInitialized.current = true + } + }, [macEnvironmentReady, senderStatus]) + + const setupBodyId = 'personal-wechat-first-use-setup' + const macPrimaryAction = resolveMacSendPrimaryAction({ + runtime: macRuntimeAvailability, + license: macLicenseStatus, + senderStatus, + binding, + detecting: loading || detecting + }) return ( <> @@ -279,7 +546,13 @@ export function PersonalWechatSendPage({ - {loading ? '检测中' : macUnavailable ? '暂不可用' : capabilityLabel[pageStatus]} + {loading + ? '检测中' + : macUnavailable + ? '没有微信发送能力' + : macComponentError + ? '发送组件异常' + : capabilityLabel[pageStatus]}
    @@ -407,18 +680,129 @@ export function PersonalWechatSendPage({ ) : isMac ? ( <> -

    配置状态

    - void bindWechat()} - onStartSending={() => - onNotice('微信消息发送能力已就绪,请在档案中选择会话开始发送。') - } - onOpenTextToSpeechSettings={onOpenTextToSpeechSettings} - /> + {/* 发送能力授权卡片:仅在加载了发送组件的档位渲染。 + OSS(runtime_missing)下不渲染,保证免费版不出现授权入口。 */} + {macRuntimeAvailability?.state === 'available' ? ( + + ) : null} +
    +
    + 微信发送环境 + + {loading + ? '正在检查环境' + : macUnavailable + ? '当前版本没有微信发送能力' + : macComponentError + ? '发送组件缺失或异常' + : macEnvironmentReady + ? '运行环境已就绪' + : '需要完成配置'} + +
    +
    + {[ + ['运行时正常', Boolean(senderStatus?.runtimeReady)], + ['微信已绑定', macBound], + ['发送组件正常', Boolean(senderStatus?.canSend)] + ].map(([label, complete]) => ( +
    + + {label} + {loading ? '检测中' : complete ? '正常' : '待完成'} +
    + ))} +
    + {senderStatus && macRuntimeAvailability?.state === 'available' ? ( +
    + {( + [ + ['文字', senderStatus.canSendText], + ['图片', senderStatus.canSendImage], + ['语音', senderStatus.canSendVoice] + ] as const + ).map(([label, available]) => ( + + {label} {available ? '可用' : '未就绪'} + + ))} +
    + ) : null} + + +
    + +
    +
    + {macUnavailable ? ( + <> +

    发送能力授权

    + + + ) : null} ) : null} diff --git a/src/renderer/src/styles/settings.scss b/src/renderer/src/styles/settings.scss index a571ef6..df123ac 100644 --- a/src/renderer/src/styles/settings.scss +++ b/src/renderer/src/styles/settings.scss @@ -249,6 +249,248 @@ background: var(--wxex-bg-elevated); padding: 24px 26px; } +.mac-pro-license-card, +.mac-wechat-environment-card { + display: grid; + gap: 14px; + min-width: 0; + padding: 20px 22px; +} +.mac-pro-license-header, +.mac-wechat-environment-header { + display: flex; + min-width: 0; + align-items: center; + justify-content: space-between; + gap: 12px; + + > strong { + color: var(--wxex-text-primary); + font-size: 15px; + font-weight: 650; + } +} +.mac-pro-license-status, +.mac-wechat-environment-status { + flex: 0 0 auto; + color: var(--wxex-text-secondary); + font-size: 12px; +} +.mac-pro-license-status.is-ready, +.mac-wechat-environment-status.is-ready, +.mac-wechat-status-item .is-ready, +.mac-wechat-capability-details .is-ready { + color: var(--wxex-success); +} +.mac-pro-license-status.is-error { + color: var(--wxex-danger); +} +.mac-pro-license-status.is-neutral, +.mac-wechat-environment-status.is-neutral { + color: var(--wxex-text-muted); +} +.mac-pro-device-row { + display: flex; + min-width: 0; + align-items: center; + gap: 10px; + border-radius: var(--wxex-radius-md); + background: color-mix(in srgb, var(--wxex-text-primary) 4%, transparent); + padding: 10px 12px; +} +.mac-pro-device-value { + display: grid; + min-width: 0; + flex: 1; + gap: 4px; + + > span { + color: var(--wxex-text-muted); + font-size: 11px; + } + + code { + overflow: hidden; + color: var(--wxex-text-primary); + font-size: 13px; + text-overflow: ellipsis; + white-space: nowrap; + } +} +.mac-pro-license-hint { + margin: -5px 0 0; + color: var(--wxex-text-secondary); + font-size: 12px; +} +.mac-pro-license-features { + display: flex; + flex-wrap: wrap; + gap: 6px; + + > span { + border-radius: 999px; + background: color-mix(in srgb, var(--wxex-text-primary) 5%, transparent); + padding: 3px 8px; + color: var(--wxex-text-secondary); + font-size: 11px; + } +} +.mac-pro-license-meta { + display: flex; + flex-wrap: wrap; + gap: 8px 24px; + color: var(--wxex-text-muted); + font-size: 11px; + + strong { + margin-left: 4px; + color: var(--wxex-text-secondary); + font-weight: 550; + } +} +.mac-pro-license-footer { + display: flex; + min-width: 0; + align-items: center; + justify-content: space-between; + gap: 12px; +} +.mac-pro-identity-note { + margin: 0; +} +.mac-wechat-status-grid { + display: grid; + grid-template-columns: repeat(3, minmax(0, 1fr)); + gap: 8px; +} +.mac-wechat-status-item { + display: grid; + min-width: 0; + justify-items: center; + gap: 5px; + border-radius: var(--wxex-radius-md); + background: color-mix(in srgb, var(--wxex-text-primary) 3%, transparent); + padding: 12px 8px; + text-align: center; + + > span { + font-size: 18px; + line-height: 1; + } + + .is-pending { + color: var(--wxex-text-muted); + } + + strong { + color: var(--wxex-text-primary); + font-size: 12px; + font-weight: 550; + } + + small { + color: var(--wxex-text-muted); + font-size: 10px; + } +} +.mac-wechat-capability-details { + display: flex; + flex-wrap: wrap; + gap: 6px 14px; + color: var(--wxex-text-muted); + font-size: 11px; + + .is-pending { + color: var(--wxex-text-muted); + } +} +.mac-wechat-setup-toggle { + display: flex; + width: 100%; + align-items: center; + justify-content: space-between; + gap: 12px; + border: 0; + border-top: 1px solid var(--wxex-border); + background: transparent; + padding: 12px 0 0; + color: var(--wxex-text-primary); + cursor: pointer; + font: inherit; + font-size: 13px; + font-weight: 600; + text-align: left; + + &:focus-visible { + border-radius: 4px; + outline: 2px solid var(--wxex-brand); + outline-offset: 3px; + } +} +.mac-wechat-setup-chevron { + color: var(--wxex-text-muted); + font-size: 18px; + transition: transform 160ms ease; +} +.mac-wechat-setup-toggle[aria-expanded='true'] .mac-wechat-setup-chevron { + transform: rotate(180deg); +} +.mac-wechat-setup-content { + min-width: 0; + + &[hidden] { + display: none; + } + + .personal-wechat-setup { + gap: 12px; + border: 0; + padding: 2px 0 0; + } + + .personal-wechat-setup-heading h2, + .personal-wechat-eyebrow { + display: none; + } +} +.mac-wechat-primary-action { + padding-top: 2px; +} +@media (prefers-reduced-motion: reduce) { + .mac-wechat-setup-chevron { + transition: none; + } +} +@media (max-width: 560px) { + .mac-pro-license-card, + .mac-wechat-environment-card { + padding: 16px; + } + + .mac-pro-license-header, + .mac-wechat-environment-header { + align-items: flex-start; + flex-direction: column; + gap: 4px; + } + + .mac-wechat-status-grid { + gap: 5px; + } + + .mac-wechat-status-item { + padding: 10px 4px; + + strong { + font-size: 10px; + } + } + + .mac-pro-license-meta { + flex-direction: column; + gap: 5px; + } +} .settings-account-overview { display: grid; grid-template-columns: minmax(190px, 1fr) minmax(220px, 1fr) auto; diff --git a/src/shared/personal-wechat-mac-license.ts b/src/shared/personal-wechat-mac-license.ts new file mode 100644 index 0000000..850e355 --- /dev/null +++ b/src/shared/personal-wechat-mac-license.ts @@ -0,0 +1,149 @@ +/** + * macOS 设备授权接口的 wire 类型。 + * 所有字段都由 `parseMacLicenseStatus` 运行时校验后才会交给上层使用。 + */ + +export type MacLicenseState = + | 'unlicensed' // no license for this device + | 'valid' // online check passed in this process + | 'cached' // local cache verified, not re-confirmed online + | 'expired' + | 'revoked' + | 'device_mismatch' // token belongs to a different device + | 'identity_error' // device key unusable + | 'server_unavailable' // network / 5xx; cache may still hold + | 'checking' // an online refresh is in flight + | 'unsupported' // host is running but has no /license endpoints (old build) + | 'runtime_missing' // host not reachable / runtime absent + | 'platform_unsupported' // not macOS native (Windows / OSS) + +const MAC_LICENSE_STATES = new Set([ + 'unlicensed', + 'valid', + 'cached', + 'expired', + 'revoked', + 'device_mismatch', + 'identity_error', + 'server_unavailable', + 'checking', + 'unsupported', + 'runtime_missing', + 'platform_unsupported' +]) + +export interface MacLicenseStatus { + deviceId: string | null + state: MacLicenseState + authorized: boolean + source: 'online' | 'cache' | 'none' + features: string[] + lastCheckedAt: string | null + licenseExpiresAt: string | null + tokenExpiresAt: string | null + message: string + /** False when the running host predates the license endpoints (404). */ + runtimeProtocolSupported?: boolean + /** Host-reported numeric TM_WECHAT_* code when a refresh failed. */ + errorCode?: number | null +} + +const DEVICE_ID_PATTERN = /^mac_[0-9a-f]{64}$/ + +function asOptionalString(value: unknown): string | null { + return typeof value === 'string' && value.length > 0 ? value : null +} + +function asOptionalIsoDate(value: unknown): string | null { + if (typeof value !== 'string' || value.length === 0) return null + // Accept RFC3339 (what the native core emits); reject obvious garbage. + if (!/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}/.test(value)) return null + return value +} + +function asStringArray(value: unknown): string[] { + if (!Array.isArray(value)) return [] + return value.filter((entry): entry is string => typeof entry === 'string') +} + +/** + * 把任意 JSON 校验成 MacLicenseStatus;无法确认的字段一律落到安全默认值。 + * `authorized` 由 state 重算,伪造的 `authorized: true` 覆盖不了已撤销状态。 + */ +export function parseMacLicenseStatus(raw: unknown): MacLicenseStatus { + const base: MacLicenseStatus = { + deviceId: null, + state: 'unlicensed', + authorized: false, + source: 'none', + features: [], + lastCheckedAt: null, + licenseExpiresAt: null, + tokenExpiresAt: null, + message: '当前设备暂无发送能力授权' + } + if (raw === null || typeof raw !== 'object') return base + const record = raw as Record + + const deviceId = asOptionalString(record.deviceId) + if (deviceId !== null && DEVICE_ID_PATTERN.test(deviceId)) { + base.deviceId = deviceId + } + + const state = asOptionalString(record.state) + if (state !== null && MAC_LICENSE_STATES.has(state as MacLicenseState)) { + base.state = state as MacLicenseState + } + + const source = asOptionalString(record.source) + if (source === 'online' || source === 'cache' || source === 'none') { + base.source = source + } + + base.features = asStringArray(record.features) + base.lastCheckedAt = asOptionalIsoDate(record.lastCheckedAt) + base.licenseExpiresAt = asOptionalIsoDate(record.licenseExpiresAt) + base.tokenExpiresAt = asOptionalIsoDate(record.tokenExpiresAt) + + const message = asOptionalString(record.message) + if (message !== null) base.message = message + + if (typeof record.runtimeProtocolSupported === 'boolean') { + base.runtimeProtocolSupported = record.runtimeProtocolSupported + } + if (typeof record.errorCode === 'number' && Number.isFinite(record.errorCode)) { + base.errorCode = record.errorCode + } + + /* + * authorized is DERIVED, not copied: only a small whitelist of states may + * present as authorized, and even then the payload's own boolean must agree. + * This keeps a forged {"authorized": true} from flipping a revoked state. + */ + const trustedStates: ReadonlySet = new Set(['valid', 'cached']) + base.authorized = trustedStates.has(base.state) && record.authorized === true + + return base +} + +/** + * Build the "runtime missing / old host" status without a network round-trip. + * Used when the host is down or answered 404 on /license/status. + */ +export function offlineMacLicenseStatus( + state: 'runtime_missing' | 'unsupported' | 'platform_unsupported' | 'server_unavailable', + message: string +): MacLicenseStatus { + return { + deviceId: null, + state, + authorized: false, + source: 'none', + features: [], + lastCheckedAt: null, + licenseExpiresAt: null, + tokenExpiresAt: null, + message, + runtimeProtocolSupported: state === 'unsupported' ? false : undefined + } +} diff --git a/src/shared/personal-wechat-mac-runtime.ts b/src/shared/personal-wechat-mac-runtime.ts index 3e566c3..a253134 100644 --- a/src/shared/personal-wechat-mac-runtime.ts +++ b/src/shared/personal-wechat-mac-runtime.ts @@ -15,6 +15,13 @@ export type MacWechatRuntimeLifecycle = | 'crashed_unbound' // died while unbound — safe to auto-restart | 'crashed_bound' // died while bound — WeChat keeps an orphan agent +export type MacWechatSendRuntimeAvailability = 'unavailable' | 'component_error' | 'available' + +export interface MacWechatSendRuntimeAvailabilityResult { + state: MacWechatSendRuntimeAvailability + message: string +} + export type MacWechatHostRuntimeState = | 'not_initialized' | 'wechat_not_running' diff --git a/src/shared/personal-wechat-mac-send-action.ts b/src/shared/personal-wechat-mac-send-action.ts new file mode 100644 index 0000000..debc924 --- /dev/null +++ b/src/shared/personal-wechat-mac-send-action.ts @@ -0,0 +1,103 @@ +import type { MacLicenseStatus } from './personal-wechat-mac-license' +import type { MacWechatSendRuntimeAvailabilityResult } from './personal-wechat-mac-runtime' +import type { PersonalWechatSenderStatus } from './personal-wechat' + +export type MacSendPrimaryActionKind = 'none' | 'bind' | 'send' + +export interface MacSendPrimaryAction { + label: string + disabled: boolean + loading: boolean + action: MacSendPrimaryActionKind + reason: + | 'runtime_unavailable' + | 'runtime_error' + | 'license_pending' + | 'license_invalid' + | 'license_feature_denied' + | 'binding' + | 'unbound' + | 'initializing' + | 'ready' +} + +export function hasValidWechatLicense(license: MacLicenseStatus | null): boolean { + if ( + !license || + !license.authorized || + (license.state !== 'valid' && license.state !== 'cached') || + !license.features.includes('wechat') + ) { + return false + } + const tokenExpiresAt = license.tokenExpiresAt ? Date.parse(license.tokenExpiresAt) : Number.NaN + return Number.isFinite(tokenExpiresAt) && tokenExpiresAt > Date.now() +} + +export function resolveMacSendPrimaryAction(input: { + runtime: MacWechatSendRuntimeAvailabilityResult | null + license: MacLicenseStatus | null + senderStatus: PersonalWechatSenderStatus | null + binding: boolean + detecting: boolean +}): MacSendPrimaryAction { + const { runtime, license, senderStatus, binding, detecting } = input + const result = ( + label: string, + disabled: boolean, + loading: boolean, + action: MacSendPrimaryActionKind, + reason: MacSendPrimaryAction['reason'] + ): MacSendPrimaryAction => ({ label, disabled, loading, action, reason }) + + if (!runtime || (detecting && !senderStatus)) { + return result('正在检查发送组件…', true, true, 'none', 'runtime_error') + } + if (runtime.state === 'unavailable') { + return result('当前版本没有微信发送能力', true, false, 'none', 'runtime_unavailable') + } + if (runtime.state === 'component_error') { + return result('发送组件缺失或异常', true, false, 'none', 'runtime_error') + } + if (license === null) { + return result('正在检测授权…', true, true, 'none', 'license_pending') + } + if (license.state === 'valid' || license.state === 'cached') { + if (license.authorized && !license.features.includes('wechat')) { + return result('未开通微信发送', true, false, 'none', 'license_feature_denied') + } + if (hasValidWechatLicense(license)) { + if (binding) return result('正在绑定…', true, true, 'none', 'binding') + const bound = Boolean( + senderStatus && + (senderStatus.state === 'online' || + Boolean( + senderStatus.wechatPid && + senderStatus.boundWechatPid === senderStatus.wechatPid && + senderStatus.attachReady && + senderStatus.baseAddressReady + )) + ) + if (!bound) return result('绑定微信', false, false, 'bind', 'unbound') + if (senderStatus?.canSend) return result('开始发送', false, false, 'send', 'ready') + return result('正在准备发送能力…', true, detecting, 'none', 'initializing') + } + } + const bound = Boolean( + senderStatus && + (senderStatus.state === 'online' || + Boolean( + senderStatus.wechatPid && + senderStatus.boundWechatPid === senderStatus.wechatPid && + senderStatus.attachReady && + senderStatus.baseAddressReady + )) + ) + return result( + bound ? '授权后可开始发送' : '授权后可绑定微信', + true, + false, + 'none', + 'license_invalid' + ) +} diff --git a/tests/component/personal-wechat-send-page.test.tsx b/tests/component/personal-wechat-send-page.test.tsx index bdf5201..8b343a6 100644 --- a/tests/component/personal-wechat-send-page.test.tsx +++ b/tests/component/personal-wechat-send-page.test.tsx @@ -58,7 +58,25 @@ describe('PersonalWechatSendPage on macOS', () => { value: { getPersonalWechatSendCapability: getCapability, getPersonalWechatSenderStatus: getSenderStatus, - rebindPersonalWechatSender: rebindSender + rebindPersonalWechatSender: rebindSender, + // 发送能力授权卡所需的两个入口。页面在 Native 档位会调用它们, + // 缺 mock 会让 refresh 抛错、整页停在错误态。 + getMacSendRuntimeAvailability: vi.fn(async () => ({ + state: 'available', + message: '微信发送组件可用' + })), + getMacLicenseStatus: vi.fn(async () => ({ + deviceId: null, + state: 'unlicensed', + authorized: false, + source: 'none', + features: [], + lastCheckedAt: null, + licenseExpiresAt: null, + tokenExpiresAt: null, + message: '当前设备暂无发送能力授权' + })), + refreshMacLicense: vi.fn() } }) }) @@ -66,7 +84,9 @@ describe('PersonalWechatSendPage on macOS', () => { it('shows the native runtime readiness', async () => { render() - expect(await screen.findByText('微信消息发送已配置完成')).toBeVisible() + // 页面重构后「就绪」的落点从 SetupGuide 尾部文案变成了「微信发送环境」卡片的状态标签; + // 断言改到新位置,语义仍是“运行时准备好了”。 + expect(await screen.findByText('运行环境已就绪')).toBeVisible() expect(screen.getAllByText('已就绪')).not.toHaveLength(0) expect(screen.queryByText('查看支持的微信版本')).not.toBeInTheDocument() expect(screen.queryByText('高级诊断')).not.toBeInTheDocument() diff --git a/tests/component/personal-wechat-unavailable.test.tsx b/tests/component/personal-wechat-unavailable.test.tsx index d5c28d5..da1a6f9 100644 --- a/tests/component/personal-wechat-unavailable.test.tsx +++ b/tests/component/personal-wechat-unavailable.test.tsx @@ -1,4 +1,4 @@ -import { render, screen } from '@testing-library/react' +import { fireEvent, render, screen, waitFor } from '@testing-library/react' import { beforeEach, describe, expect, it, vi } from 'vitest' import { PersonalWechatSetupGuide } from '../../src/renderer/src/components/chat/PersonalWechatSetupGuide' @@ -41,6 +41,10 @@ describe('personal WeChat unavailable product state', () => { Object.defineProperty(window, 'api', { configurable: true, value: { + getMacSendRuntimeAvailability: vi.fn(async () => ({ + state: 'available', + message: '微信发送组件可用' + })), getPersonalWechatSendCapability: vi.fn(async () => ({ supported: true, ready: false, @@ -50,7 +54,19 @@ describe('personal WeChat unavailable product state', () => { message: '暂无发送能力', error: '暂无发送能力' })), - getPersonalWechatSenderStatus: vi.fn(async () => unavailableStatus) + getPersonalWechatSenderStatus: vi.fn(async () => unavailableStatus), + getMacLicenseStatus: vi.fn(async () => ({ + deviceId: `mac_${'c'.repeat(64)}`, + state: 'unlicensed', + authorized: false, + source: 'none', + features: [], + lastCheckedAt: null, + licenseExpiresAt: null, + tokenExpiresAt: null, + message: '当前设备暂无发送能力授权' + })), + refreshMacLicense: vi.fn() } }) }) @@ -85,12 +101,195 @@ describe('personal WeChat unavailable product state', () => { render() expect(await screen.findByRole('heading', { name: '先准备好微信消息功能' })).toBeVisible() - expect(screen.getByRole('button', { name: '绑定微信' })).toBeDisabled() + expect(screen.getByRole('button', { name: '授权后可绑定微信' })).toBeDisabled() + expect(screen.getByRole('region', { name: '微信发送环境' })).toBeVisible() + expect(screen.getByText('运行时正常')).toBeVisible() + expect(screen.getByText('微信已绑定')).toBeVisible() + expect(screen.getByText('发送组件正常')).toBeVisible() + expect(screen.getByRole('button', { name: '首次使用配置' })).toHaveAttribute( + 'aria-expanded', + 'true' + ) + expect(await screen.findByRole('region', { name: '发送能力授权' })).toBeVisible() + expect(screen.queryByText(/发送能力属授权制,需要联系群主/)).not.toBeInTheDocument() + expect(screen.queryByRole('link', { name: '这里' })).not.toBeInTheDocument() + expect(screen.queryByText(/manifest|dylib|runtime missing|文件缺失/i)).not.toBeInTheDocument() + }) + + it('shows real environment status and keeps first-use details collapsed when ready', async () => { + Object.defineProperty(window, 'api', { + configurable: true, + value: { + getMacSendRuntimeAvailability: vi.fn(async () => ({ + state: 'available', + message: '微信发送组件可用' + })), + getPersonalWechatSendCapability: vi.fn(async () => ({ + supported: true, + ready: true, + status: 'ready', + capabilities: { text: true, image: true, voice: true }, + senderStatus: readyStatus, + message: '已就绪' + })), + getPersonalWechatSenderStatus: vi.fn(async () => readyStatus), + getMacLicenseStatus: vi.fn(async () => ({ + ...licenseStatus, + state: 'revoked', + authorized: false + })), + refreshMacLicense: vi.fn() + } + }) + + render() + + expect(await screen.findByText('运行环境已就绪')).toBeVisible() + expect(screen.getAllByText('正常')).toHaveLength(3) + expect(screen.getByRole('button', { name: '授权后可开始发送' })).toBeDisabled() + expect(screen.getByRole('button', { name: '首次使用配置' })).toHaveAttribute( + 'aria-expanded', + 'false' + ) + expect(screen.queryByRole('button', { name: '绑定微信' })).not.toBeInTheDocument() + expect(await screen.findByText('授权已撤销')).toBeVisible() + + fireEvent.click(screen.getByRole('button', { name: '首次使用配置' })) + expect(screen.getByRole('button', { name: '首次使用配置' })).toHaveAttribute( + 'aria-expanded', + 'true' + ) + expect(screen.queryByRole('button', { name: '绑定微信' })).not.toBeInTheDocument() + expect(screen.queryByRole('button', { name: '开始发送' })).not.toBeInTheDocument() + expect(screen.getAllByRole('listitem')).toHaveLength(2) + expect(screen.getByText('每个微信进程只能绑定一次')).toBeVisible() + expect(screen.getByText(/4\.1\.13以下请保持微信未登录窗口状态/)).toBeVisible() + expect(screen.getByText('4.1.13以上登录状态微信直接点击“绑定微信”')).toBeVisible() + expect(screen.queryByText('能力检测')).not.toBeInTheDocument() + expect(screen.queryByText('文字消息')).not.toBeInTheDocument() + expect(screen.queryByText('图片消息')).not.toBeInTheDocument() + expect(screen.queryByText('语音消息')).not.toBeInTheDocument() + }) + + it('copies the full device id and shows refresh loading without disabling copy', async () => { + const deviceId = `mac_${'a'.repeat(64)}` + let resolveRefresh: ((value: typeof licenseStatus) => void) | undefined + const refreshMacLicense = vi.fn( + () => new Promise((resolve) => (resolveRefresh = resolve)) + ) + Object.defineProperty(navigator, 'clipboard', { + configurable: true, + value: { writeText: vi.fn(async () => undefined) } + }) + Object.defineProperty(window, 'api', { + configurable: true, + value: { + getMacSendRuntimeAvailability: vi.fn(async () => ({ + state: 'available', + message: '微信发送组件可用' + })), + getPersonalWechatSendCapability: vi.fn(async () => ({ + supported: true, + ready: false, + status: 'unconfigured', + capabilities: { text: false, image: false, voice: false }, + senderStatus: readyStatus, + message: '未配置' + })), + getPersonalWechatSenderStatus: vi.fn(async () => readyStatus), + getMacLicenseStatus: vi.fn(async () => ({ ...licenseStatus, deviceId, state: 'expired' })), + refreshMacLicense + } + }) + + render() + const copyButton = await screen.findByRole('button', { name: '复制完整设备 ID' }) + fireEvent.click(copyButton) + await waitFor(() => expect(navigator.clipboard.writeText).toHaveBeenCalledWith(deviceId)) + expect(await screen.findByText('授权已过期')).toBeVisible() + + fireEvent.click(screen.getByRole('button', { name: '重新检测授权' })) + expect(await screen.findByRole('button', { name: '检测中…' })).toBeDisabled() + expect(copyButton).toBeEnabled() + resolveRefresh?.({ ...licenseStatus, deviceId, state: 'valid', authorized: true }) + }) + + it('does not query or render License when the send runtime is unavailable', async () => { + const getMacLicenseStatus = vi.fn() + Object.defineProperty(window, 'api', { + configurable: true, + value: { + getMacSendRuntimeAvailability: vi.fn(async () => ({ + state: 'unavailable', + message: '当前版本没有微信发送能力' + })), + getMacLicenseStatus, + getPersonalWechatSendCapability: vi.fn(), + getPersonalWechatSenderStatus: vi.fn() + } + }) + + render() + + expect(await screen.findByRole('button', { name: '当前版本没有微信发送能力' })).toBeDisabled() expect(screen.getByText(/发送能力属授权制,需要联系群主/)).toBeVisible() expect(screen.getByRole('link', { name: '这里' })).toHaveAttribute( 'href', 'https://github.com/Wxw-Gu/TraceMemo#-交流与反馈' ) - expect(screen.queryByText(/manifest|dylib|runtime missing|文件缺失/i)).not.toBeInTheDocument() + expect(screen.queryByRole('region', { name: '发送能力授权' })).not.toBeInTheDocument() + expect(getMacLicenseStatus).not.toHaveBeenCalled() + }) + + it('shows component failure without querying License when send runtime files are damaged', async () => { + const getMacLicenseStatus = vi.fn() + Object.defineProperty(window, 'api', { + configurable: true, + value: { + getMacSendRuntimeAvailability: vi.fn(async () => ({ + state: 'component_error', + message: '发送组件缺失或异常:manifest missing' + })), + getMacLicenseStatus, + getPersonalWechatSendCapability: vi.fn(), + getPersonalWechatSenderStatus: vi.fn() + } + }) + + render() + + expect(await screen.findByRole('button', { name: '发送组件缺失或异常' })).toBeDisabled() + expect(screen.getAllByText('发送组件缺失或异常').length).toBeGreaterThan(0) + expect(screen.queryByText(/发送能力属授权制,需要联系群主/)).not.toBeInTheDocument() + expect(getMacLicenseStatus).not.toHaveBeenCalled() + expect(screen.queryByRole('region', { name: '发送能力授权' })).not.toBeInTheDocument() }) }) + +const readyStatus: PersonalWechatSenderStatus = { + ...unavailableStatus, + state: 'online', + wechatRunning: true, + wechatPid: 1234, + boundWechatPid: 1234, + endpointReady: true, + runtimeReady: true, + attachReady: true, + baseAddressReady: true, + canSend: true, + canSendText: true, + canSendImage: true, + canSendVoice: true +} + +const licenseStatus = { + deviceId: `mac_${'b'.repeat(64)}`, + state: 'valid' as const, + authorized: true, + source: 'online' as const, + features: ['wechat', 'api'], + lastCheckedAt: '2026-11-04T09:44:00+08:00', + licenseExpiresAt: '2027-11-03T00:00:00+08:00', + tokenExpiresAt: null, + message: '已授权' +} diff --git a/tests/unit/license-refresh-failure.test.ts b/tests/unit/license-refresh-failure.test.ts new file mode 100644 index 0000000..3046389 --- /dev/null +++ b/tests/unit/license-refresh-failure.test.ts @@ -0,0 +1,70 @@ +import { describe, expect, it } from 'vitest' + +import { resolveLicenseRefreshFailure } from '../../src/main/services/mac-wechat-runtime-manager' +import type { MacLicenseStatus } from '../../src/shared/personal-wechat-mac-license' + +const DEVICE_ID = `mac_${'a'.repeat(64)}` + +function status(overrides: Partial = {}): MacLicenseStatus { + return { + deviceId: DEVICE_ID, + state: 'cached', + authorized: true, + source: 'cache', + features: ['wechat'], + lastCheckedAt: '2026-11-04T07:00:00Z', + licenseExpiresAt: null, + tokenExpiresAt: '2026-11-05T07:00:00Z', + message: '授权有效(本地缓存)', + ...overrides + } +} + +const DIAGNOSTIC = '无法连接授权服务器,请检查网络后重试' + +describe('resolveLicenseRefreshFailure', () => { + it('有效缓存时保留授权,并把本次失败写进诊断信息', () => { + const result = resolveLicenseRefreshFailure(status(), DIAGNOSTIC) + + // 授权状态不变 —— 网络故障不能让已授权设备变成未授权。 + expect(result.authorized).toBe(true) + expect(result.state).toBe('cached') + expect(result.deviceId).toBe(DEVICE_ID) + expect(result.features).toEqual(['wechat']) + // 但这次失败必须可见,不能被快照整个盖掉。 + expect(result.message).toContain('本次刷新失败') + expect(result.message).toContain(DIAGNOSTIC) + expect(result.message).toContain('本地缓存授权') + }) + + it('无有效缓存时明确报 server_unavailable,而不是未授权或已撤销', () => { + const result = resolveLicenseRefreshFailure(null, DIAGNOSTIC) + + expect(result.state).toBe('server_unavailable') + expect(result.authorized).toBe(false) + expect(result.state).not.toBe('revoked') + expect(result.state).not.toBe('unlicensed') + expect(result.message).toBe(DIAGNOSTIC) + }) + + it('快照存在但未授权时同样按网络故障处理', () => { + const result = resolveLicenseRefreshFailure( + status({ state: 'unlicensed', authorized: false, message: '当前设备暂无发送能力授权' }), + DIAGNOSTIC + ) + + expect(result.state).toBe('server_unavailable') + expect(result.authorized).toBe(false) + expect(result.message).toBe(DIAGNOSTIC) + }) + + it('不把 revoked 快照改写成授权有效', () => { + const result = resolveLicenseRefreshFailure( + status({ state: 'revoked', authorized: false, message: '授权已被撤销' }), + DIAGNOSTIC + ) + + expect(result.authorized).toBe(false) + expect(result.state).toBe('server_unavailable') + }) +})