diff --git a/.gitignore b/.gitignore index a74f363..e00ab35 100644 --- a/.gitignore +++ b/.gitignore @@ -29,3 +29,4 @@ task_plan.md *tm-wcdb-config-helper* debug-originals +/build/mac-staging/ diff --git a/electron.vite.config.ts b/electron.vite.config.ts index 90fe99c..987c7db 100644 --- a/electron.vite.config.ts +++ b/electron.vite.config.ts @@ -2,9 +2,12 @@ import { resolve } from 'path' import { defineConfig } from 'electron-vite' import react from '@vitejs/plugin-react' +const editionOutDir = process.env.TRACEMEMO_EDITION_OUT_DIR + export default defineConfig({ main: { build: { + ...(editionOutDir ? { outDir: editionOutDir } : {}), rollupOptions: { input: { index: resolve('src/main/index.ts'), @@ -20,8 +23,9 @@ export default defineConfig({ } } }, - preload: {}, + preload: editionOutDir ? { build: { outDir: editionOutDir } } : {}, renderer: { + ...(editionOutDir ? { build: { outDir: editionOutDir } } : {}), resolve: { alias: { '@renderer': resolve('src/renderer/src') diff --git a/package.json b/package.json index 806204a..1986c29 100644 --- a/package.json +++ b/package.json @@ -63,6 +63,8 @@ "build:win": "npm run typecheck && npm run prepare:win-runtime && electron-vite build && electron-builder --config electron-builder.win.yml --win --x64", "build:mac:arm64": "npm run typecheck && npm run prepare:ffmpeg:mac:arm64 && electron-vite build && electron-builder --config electron-builder.yml --mac --arm64", "build:mac:arm64:send-runtime": "npm run typecheck && npm run prepare:ffmpeg:mac:arm64 && electron-vite build && cross-env TM_SEND_RUNTIME_BUILD=1 electron-builder --config electron-builder.send-runtime.yml --mac --arm64", + "build:mac:public": "node scripts/build-macos-edition.cjs public", + "build:mac:native": "node scripts/build-macos-edition.cjs native", "build:mac:x64": "npm run typecheck && npm run prepare:ffmpeg:mac:x64 && electron-vite build && electron-builder --config electron-builder.yml --mac --x64", "release": "npm run release:mac && npm run release:win", "release:mac": "npm run typecheck && electron-vite build && npm run release:mac:arm64 && npm run release:mac:x64", @@ -175,4 +177,4 @@ "ffmpeg-static" ] } -} \ No newline at end of file +} diff --git a/scripts/after-pack.cjs b/scripts/after-pack.cjs index c2f990c..202e9be 100644 --- a/scripts/after-pack.cjs +++ b/scripts/after-pack.cjs @@ -1,5 +1,6 @@ /* eslint-disable @typescript-eslint/no-require-imports, @typescript-eslint/explicit-function-return-type */ -const { chmodSync, existsSync, readdirSync, rmSync } = require('node:fs') +const { chmodSync, existsSync, readFileSync, readdirSync, rmSync } = require('node:fs') +const { createHash } = require('node:crypto') const { execFileSync } = require('node:child_process') const path = require('node:path') const asar = require('@electron/asar') @@ -24,6 +25,13 @@ const REQUIRED_RUNTIME_PACKAGES = [ // every Mach-O verifies strictly; spctl still rejects ad-hoc code, which is // acceptable for the SIP-disabled customer workflow. const MACOS_HELPER_NAMES = ['xkey_helper', 'xkey_helper_4_1_13'] +const MACOS_EDITION_CODE_PATHS = [ + ['wcdb', 'macos', 'arm64', 'libwcdb_api.dylib'], + ['wcdb', 'macos', 'arm64', 'libWCDB.dylib'], + ['wcdb', 'macos', 'arm64', 'tm-wcdb-config-helper'], + ['runtime', 'darwin-arm64', 'tm-wechat-host'], + ['runtime', 'darwin-arm64', 'libtmwechat.dylib'] +] function getRuntimeResources(context) { const productName = context.packager.appInfo.productFilename @@ -45,7 +53,25 @@ function validateSilkWasmRuntime(runtimeResources) { } } -function validateFfmpegRuntime(runtimeResources, platform = process.platform) { +function validateFfmpegRuntime( + runtimeResources, + platform = process.platform, + edition = process.env.TRACEMEMO_EDITION +) { + if (platform === 'darwin' && edition) { + const editionFfmpeg = path.join(runtimeResources, 'resources', 'ffmpeg', 'ffmpeg') + if (!existsSync(editionFfmpeg)) throw new Error(`Missing staged macOS ffmpeg: ${editionFfmpeg}`) + const sharedBinary = path.join( + runtimeResources, + 'app.asar.unpacked', + 'node_modules', + 'ffmpeg-static', + 'ffmpeg' + ) + rmSync(sharedBinary, { force: true }) + chmodSync(editionFfmpeg, 0o755) + return editionFfmpeg + } const executable = platform === 'win32' ? 'ffmpeg.exe' : 'ffmpeg' const ffmpegPath = path.join( runtimeResources, @@ -61,6 +87,171 @@ function validateFfmpegRuntime(runtimeResources, platform = process.platform) { return ffmpegPath } +function validateMacEditionResources(runtimeResources, edition, platform) { + if (platform !== 'darwin') return + const resources = path.join(runtimeResources, 'resources') + const markerPath = path.join(resources, 'tracememo-build.json') + if (!existsSync(markerPath)) throw new Error(`Missing macOS edition marker: ${markerPath}`) + const marker = JSON.parse(readFileSync(markerPath, 'utf8')) + if (marker.profile !== edition) throw new Error(`Expected ${edition} bundle, found ${String(marker.profile)}`) + const wcdb = path.join(resources, 'wcdb', 'macos', 'arm64') + const api = path.join(wcdb, 'libwcdb_api.dylib') + const companion = path.join(wcdb, 'libWCDB.dylib') + const helper = path.join(wcdb, 'tm-wcdb-config-helper') + const runtime = path.join(resources, 'runtime', 'darwin-arm64') + const host = path.join(runtime, 'tm-wechat-host') + const runtimeDylib = path.join(runtime, 'libtmwechat.dylib') + const runtimeManifest = path.join(runtime, 'runtime-manifest.json') + const nativeArtifacts = [helper, host, runtimeDylib, runtimeManifest] + const presentNativeArtifacts = nativeArtifacts.filter(existsSync) + if (edition === 'public' && presentNativeArtifacts.length) { + throw new Error(`Public bundle contains native artifacts: ${presentNativeArtifacts.join(', ')}`) + } + if (edition === 'native' && presentNativeArtifacts.length !== nativeArtifacts.length) { + throw new Error('Native bundle is missing WCDB helper or WeChat runtime files') + } + for (const protectedPath of [path.join(resources, '1.txt'), path.join(resources, 'runtime', 'runtime.zip')]) { + if (existsSync(protectedPath)) throw new Error(`Protected file leaked into macOS bundle: ${protectedPath}`) + } + if (!existsSync(api) || !existsSync(companion)) throw new Error('macOS bundle is missing WCDB files') + if (!readBinaryArchitectures(api).includes('arm64')) throw new Error('Bundled WCDB API is not arm64') + if (!readBinaryArchitectures(companion).includes('arm64')) throw new Error('Bundled WCDB companion is not arm64') + const apiDependencies = execFileSync('/usr/bin/otool', ['-L', api], { encoding: 'utf8' }) + if (!apiDependencies.includes('@loader_path/libWCDB.dylib')) { + throw new Error('Bundled WCDB API is missing its @loader_path companion dependency') + } + const symbols = execFileSync('/usr/bin/nm', ['-gU', api], { encoding: 'utf8' }) + .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`) + } + const nativeInput = marker.nativeInput || {} + if (edition === 'public') { + if (nativeInput.libwcdbApiSha256 && createHash('sha256').update(readFileSync(api)).digest('hex') !== nativeInput.libwcdbApiSha256) { + throw new Error('Packaged public WCDB API does not match the recorded WCDB input hash') + } + if (nativeInput.libWCDBSha256 && createHash('sha256').update(readFileSync(companion)).digest('hex') !== nativeInput.libWCDBSha256) { + throw new Error('Packaged public WCDB companion does not match the recorded WCDB input hash') + } + } + const requiredSymbols = [ + 'wcdb_get_messages', + 'wcdb_get_group_members_batch', + 'wcdb_start_monitor_pipe', + ...(edition === 'native' + ? [ + 'wcdb_msg_insert_set_switch', + 'wcdb_msg_insert_get_switches', + 'wcdb_msg_insert_list_shard_catalog', + 'wcdb_msg_insert_ensure_rooms_rules', + 'wcdb_msg_insert_get_rooms_status', + 'wcdb_msg_insert_inspect_shard', + 'wcdb_msg_insert_insert_local_notice', + 'wcdb_msg_insert_insert_local_notice_ex', + 'wcdb_msg_insert_sync_display_names' + ] + : []) + ] + const missingSymbols = requiredSymbols.filter((symbol) => !symbols.includes(symbol)) + if (missingSymbols.length) throw new Error(`${edition} WCDB API is missing exports: ${missingSymbols.join(', ')}`) + const ffmpeg = path.join(resources, 'ffmpeg', 'ffmpeg') + if (!existsSync(ffmpeg) || !readBinaryArchitectures(ffmpeg).includes('arm64')) { + throw new Error(`macOS arm64 FFmpeg is missing or wrong architecture: ${ffmpeg}`) + } + if (marker.ffmpegSha256 && createHash('sha256').update(readFileSync(ffmpeg)).digest('hex') !== marker.ffmpegSha256) { + throw new Error('Packaged FFmpeg does not match its recorded staged hash') + } + for (const relative of [ + 'licenses/ffmpeg-static/LICENSE', + 'licenses/ffmpeg-static/FFMPEG-LICENSE.txt', + 'licenses/ffmpeg-static/FFMPEG-BUILD-INFO.txt' + ]) { + if (!existsSync(path.join(resources, relative))) { + throw new Error(`Missing FFmpeg license/build notice: ${relative}`) + } + } + if (edition === 'native') { + for (const binary of [helper, host, runtimeDylib]) { + if (!readBinaryArchitectures(binary).includes('arm64')) { + throw new Error(`Native binary lacks arm64 architecture: ${binary}`) + } + } + const manifest = JSON.parse(readFileSync(runtimeManifest, 'utf8')) + if (manifest.runtime !== 'tm-wechat-native') throw new Error('Runtime Manifest runtime name is invalid') + if (manifest.platform !== 'darwin-arm64' || manifest.architecture !== 'arm64' || manifest.protocolVersion !== 1) { + throw new Error('Runtime Manifest platform, architecture, or protocol is invalid') + } + for (const capability of ['text', 'image', 'voice']) { + if (!Array.isArray(manifest.capabilities) || !manifest.capabilities.includes(capability)) { + throw new Error(`Runtime Manifest is missing capability: ${capability}`) + } + } + if (!Array.isArray(manifest.supportedWechatVersions) || manifest.supportedWechatVersions.length === 0) { + throw new Error('Runtime Manifest has no supported WeChat versions') + } + const dylib = readFileSync(runtimeDylib) + for (const key of ['tmSendSourceSha256', 'addressProfileSha256']) { + if (!/^[a-f0-9]{64}$/.test(manifest[key] || '') || !dylib.includes(Buffer.from(manifest[key]))) { + throw new Error(`Runtime embedded hash mismatch: ${key}`) + } + } + if (!execFileSync('/usr/bin/otool', ['-L', helper], { encoding: 'utf8' }).includes('@loader_path/libwcdb_api.dylib')) { + throw new Error('Native helper is missing its @loader_path WCDB API dependency') + } + const actualRuntimeManifest = JSON.parse(readFileSync(runtimeManifest, 'utf8')) + if (actualRuntimeManifest.runtime !== 'tm-wechat-native' || + actualRuntimeManifest.platform !== 'darwin-arm64' || + actualRuntimeManifest.architecture !== 'arm64' || + actualRuntimeManifest.protocolVersion !== 1 || + !Array.isArray(actualRuntimeManifest.supportedWechatVersions) || + actualRuntimeManifest.supportedWechatVersions.length === 0) { + throw new Error('Runtime Manifest failed application compatibility checks') + } + for (const key of ['tmSendSourceSha256', 'addressProfileSha256']) { + if (!/^[a-f0-9]{64}$/.test(actualRuntimeManifest[key] || '')) { + throw new Error(`Runtime Manifest has invalid ${key}`) + } + } + const stagedFiles = marker.nativeInput?.files + if (!Array.isArray(stagedFiles) || stagedFiles.length !== 6) { + 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\//, '')) + const binary = path.join(resources, relative) + if (!existsSync(binary) || readFileSync(binary).length !== entry.bytes) { + throw new Error(`Native packaged artifact size mismatch: ${entry.path}`) + } + const digest = createHash('sha256').update(readFileSync(binary)).digest('hex') + if (digest !== entry.sha256) throw new Error(`Native packaged artifact SHA-256 mismatch: ${entry.path}`) + } + } +} + +function validateMacEditionProtectedFiles(runtimeResources) { + const asarPath = path.join(runtimeResources, 'app.asar') + if (!existsSync(asarPath)) throw new Error(`Missing packaged application archive: ${asarPath}`) + const entries = asar.listPackage(asarPath).map((entry) => entry.replaceAll('\\', '/')) + const leaked = entries.filter((entry) => + /(^|\/)1\.txt$/i.test(entry) || + /(^|\/)runtime\.zip$/i.test(entry) || + /(^|\/)\.env(?:\.|$)/i.test(entry) || + /\.(?:db|sqlite)(?:3)?$/i.test(entry) || + /\.log$/i.test(entry) + ) + if (leaked.length) throw new Error(`Sensitive file(s) leaked into app.asar: ${leaked.join(', ')}`) + for (const relative of ['1.txt', 'runtime/runtime.zip']) { + const candidate = path.join(runtimeResources, 'resources', relative) + if (existsSync(candidate)) throw new Error(`Protected file leaked into packaged resources: ${candidate}`) + } +} + function validateSherpaRuntime(runtimeResources, platform, arch) { const platformName = platform === 'win32' ? 'win' : platform const basePath = path.join( @@ -193,19 +384,28 @@ function isMacosCodeValid(targetPath, run = runCodesign) { } function findMacosHelperPaths(runtimeResources) { - return MACOS_HELPER_NAMES.map((name) => path.join(runtimeResources, 'resources', name)).filter( - (helperPath) => existsSync(helperPath) - ) + const paths = MACOS_HELPER_NAMES.map((name) => path.join(runtimeResources, 'resources', name)) + if (process.env.TRACEMEMO_EDITION) { + paths.push(...MACOS_EDITION_CODE_PATHS.map((segments) => path.join(runtimeResources, 'resources', ...segments))) + } + return paths.filter((helperPath) => existsSync(helperPath)) } function signMacosHelpers(runtimeResources, run = runCodesign) { const helperPaths = findMacosHelperPaths(runtimeResources) for (const helperPath of helperPaths) { - chmodSync(helperPath, 0o755) + if (!helperPath.endsWith('.dylib')) chmodSync(helperPath, 0o755) if (!isMacosCodeValid(helperPath, run)) { run(['--force', '--sign', '-', helperPath]) } - for (const arch of ['arm64', 'x86_64']) { + const architectures = readBinaryArchitectures(helperPath) + if (architectures.length === 0 && process.env.TRACEMEMO_EDITION) { + throw new Error(`macOS edition helper is not a supported Mach-O: ${helperPath}`) + } + const verificationArchitectures = architectures.length + ? architectures.map((arch) => (arch === 'x64' ? 'x86_64' : arch)) + : ['arm64', 'x86_64'] + for (const arch of verificationArchitectures) { try { run(['--verify', '--strict', '--arch', arch, helperPath]) } catch (error) { @@ -483,7 +683,12 @@ function isSendRuntimeBuild() { function enforceSendRuntimeBoundary( runtimeResources, platform, - bundlesSendRuntime = isSendRuntimeBuild() + bundlesSendRuntime = + process.env.TRACEMEMO_EDITION === 'native' + ? true + : process.env.TRACEMEMO_EDITION === 'public' + ? false + : isSendRuntimeBuild() ) { if (platform !== 'darwin') return null const found = findSendRuntime(runtimeResources) @@ -532,6 +737,23 @@ exports.default = async function afterPack(context) { validateSherpaRuntime(runtimeResources, context.electronPlatformName, arch) validateSystemOcrRuntime(runtimeResources, context.electronPlatformName, arch) validateKoffiRuntime(runtimeResources, context.electronPlatformName, arch) + if (context.electronPlatformName === 'darwin' && process.env.TRACEMEMO_EDITION) { + validateMacEditionResources(runtimeResources, process.env.TRACEMEMO_EDITION, context.electronPlatformName) + validateMacEditionProtectedFiles(runtimeResources) + if (process.env.TRACEMEMO_EDITION === 'public' && sendRuntime) { + throw new Error('Public edition unexpectedly includes a WeChat Runtime') + } + if (process.env.TRACEMEMO_EDITION === 'native' && !sendRuntime) { + throw new Error('Native edition is missing its WeChat Runtime') + } + if (sendRuntime) { + for (const runtimeFile of ['tm-wechat-host', 'libtmwechat.dylib', 'runtime-manifest.json']) { + if (!existsSync(path.join(sendRuntime, runtimeFile))) { + throw new Error(`Runtime file missing after packaging: ${runtimeFile}`) + } + } + } + } pruneIntelMacKeyTool(runtimeResources, context.electronPlatformName, arch) pruneForeignArchConnectors(runtimeResources, context.electronPlatformName, arch) pruneForeignArchNativeRuntimes(runtimeResources, context.electronPlatformName, arch) @@ -554,6 +776,8 @@ exports.validateSilkWasmRuntime = validateSilkWasmRuntime exports.validateSherpaRuntime = validateSherpaRuntime exports.validateSystemOcrRuntime = validateSystemOcrRuntime exports.validateKoffiRuntime = validateKoffiRuntime +exports.validateMacEditionResources = validateMacEditionResources +exports.validateMacEditionProtectedFiles = validateMacEditionProtectedFiles exports.pruneIntelMacKeyTool = pruneIntelMacKeyTool exports.pruneForeignArchConnectors = pruneForeignArchConnectors exports.pruneForeignArchNativeRuntimes = pruneForeignArchNativeRuntimes diff --git a/scripts/build-macos-edition.cjs b/scripts/build-macos-edition.cjs new file mode 100644 index 0000000..f5c0adf --- /dev/null +++ b/scripts/build-macos-edition.cjs @@ -0,0 +1,170 @@ +const fs = require('node:fs') +const path = require('node:path') +const { spawnSync } = require('node:child_process') +const { assertStagingTargetDoesNotExist, prepareEdition, validateStagedEdition } = require('./prepare-macos-edition.cjs') + +const ROOT = path.resolve(__dirname, '..') +const STAGE_ROOT = path.join(ROOT, 'build', 'mac-staging') +const OUTPUT_ROOT = path.join(ROOT, 'dist', 'mac') +const EDITIONS = ['public', 'native'] +const CONFIG_ROOT = path.join(STAGE_ROOT, 'configs') +const YAML = require('yaml') + +function run(args, env) { + const result = spawnSync(process.execPath, args, { cwd: ROOT, stdio: 'inherit', env }) + if (result.error) throw result.error + if (result.status !== 0) throw new Error(`Command failed (${result.status}): ${args.join(' ')}`) +} + +function createBuilderConfig({ edition, stageRoot, buildOutput, outputRoot, appVersion }) { + return { + appId: 'com.tracememo.app', + productName: 'TraceMemo', + afterPack: path.join(ROOT, 'scripts/after-pack.cjs'), + directories: { + buildResources: path.join(ROOT, 'build'), + output: outputRoot + }, + files: [ + { from: buildOutput, to: 'out', filter: ['**/*'] }, + 'package.json', + '!resources/**', + '!1.txt', + '!**/1.txt', + '!**/*.db', + '!**/*.sqlite*', + '!**/*.log', + '!**/runtime.zip', + '!.' + 'ai-local/**', + '!.' + 'workbuddy/**', + '!tests/**', + '!AGENTS.md', + '!**/.vscode/*', + '!src/*', + '!electron.vite.config.{js,ts,mjs,cjs}', + '!{.eslintcache,eslint.config.mjs,.prettierignore,.prettierrc.yaml,dev-app-update.yml,CHANGELOG.md,README.md}', + '!{.env,.env.*,.npmrc,pnpm-lock.yaml}', + '!{tsconfig.json,tsconfig.node.json,tsconfig.web.json}' + ], + extraMetadata: { main: 'out/main/index.js' }, + asarUnpack: [ + 'resources/**', + 'node_modules/ffmpeg-static/**', + 'node_modules/silk-wasm/**', + 'node_modules/sherpa-onnx-node/**', + 'node_modules/sherpa-onnx-*/**', + 'node_modules/@napi-rs/system-ocr/**', + 'node_modules/@napi-rs/system-ocr-*/**' + ], + extraResources: [ + { from: path.join(stageRoot, 'resources'), to: 'resources', filter: ['**/*'] }, + { from: path.join(ROOT, 'build/app-update.yml'), to: 'app-update.yml' }, + { + from: path.join(ROOT, 'docs/skill/tracememo-reader'), + to: 'skill/tracememo-reader', + filter: ['**/*'] + } + ], + mac: { + icon: path.join(ROOT, 'build/icon.icns'), + target: ['dmg'], + entitlementsInherit: path.join(ROOT, 'build/entitlements.mac.plist'), + extendInfo: { + CFBundleDisplayName: 'TraceMemo', + NSCameraUsageDescription: 'Application requests access to the device camera.', + NSMicrophoneUsageDescription: 'Application requests access to the device microphone.', + NSDocumentsFolderUsageDescription: 'Application requests access to the user documents folder.', + NSDownloadsFolderUsageDescription: 'Application requests access to the user downloads folder.' + }, + notarize: false + }, + dmg: { + artifactName: + edition === 'native' + ? `TraceMemo-${appVersion}-mac-arm64-native.dmg` + : `TraceMemo-${appVersion}-mac-arm64-public.dmg` + }, + npmRebuild: false + } +} + +function buildEdition(edition, options = {}) { + if (!EDITIONS.includes(edition)) throw new Error('Usage: build-macos-edition.cjs ') + const stageRoot = path.join(STAGE_ROOT, edition) + const outputRoot = path.join(OUTPUT_ROOT, edition) + if (fs.existsSync(stageRoot) && !options.reuseStaging) { + throw new Error(`Refusing to overwrite existing build staging: ${stageRoot}`) + } + if (fs.existsSync(outputRoot)) throw new Error(`Refusing to overwrite existing build output: ${outputRoot}`) + if (fs.existsSync(CONFIG_ROOT)) throw new Error(`Refusing to overwrite existing build config directory: ${CONFIG_ROOT}`) + const preparation = fs.existsSync(stageRoot) + ? Promise.resolve(validateStagedEdition(edition)) + : prepareEdition(edition) + if (!preparation || typeof preparation.then !== 'function') throw new Error('Edition staging preparation did not return a Promise') + return preparation.then(() => { + const buildOutput = path.join(stageRoot, 'out') + const configPath = path.join(CONFIG_ROOT, `electron-builder-${edition}.yml`) + let ownsConfigRoot = false + let buildSucceeded = false + try { + const markerPath = path.join(stageRoot, 'resources', 'tracememo-build.json') + const marker = JSON.parse(fs.readFileSync(markerPath, 'utf8')) + const packageJson = JSON.parse(fs.readFileSync(path.join(ROOT, 'package.json'), 'utf8')) + if (marker.profile !== edition || marker.appVersion !== packageJson.version) { + throw new Error('Staged edition marker does not match the current package metadata') + } + validateStagedEdition(edition) + const env = { ...process.env, TRACEMEMO_EDITION: edition, TRACEMEMO_RUNTIME_PROFILE: edition } + env.TRACEMEMO_EDITION_OUT_DIR = path.relative(ROOT, buildOutput) + run( + [ + path.join(ROOT, 'node_modules/electron-vite/bin/electron-vite.js'), + 'build', + '--outDir', + path.relative(ROOT, buildOutput) + ], + env + ) + fs.mkdirSync(CONFIG_ROOT) + ownsConfigRoot = true + const config = createBuilderConfig({ + edition, + stageRoot, + buildOutput, + outputRoot, + appVersion: packageJson.version + }) + fs.writeFileSync(configPath, YAML.stringify(config), { flag: 'wx' }) + run( + [ + path.join(ROOT, 'node_modules/electron-builder/cli.js'), + '--config', + path.relative(ROOT, configPath), + '--mac', + '--arm64' + ], + env + ) + buildSucceeded = true + } finally { + if (ownsConfigRoot) fs.rmSync(CONFIG_ROOT, { recursive: true, force: true }) + if (!buildSucceeded && fs.existsSync(outputRoot)) { + fs.rmSync(outputRoot, { recursive: true, force: true }) + } + } + }) +} + +if (require.main === module) { + try { + Promise.resolve(buildEdition(process.argv[2], { reuseStaging: process.argv[3] === '--reuse-staging' })).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 + } +} + +module.exports = { buildEdition, createBuilderConfig } diff --git a/scripts/prepare-macos-edition.cjs b/scripts/prepare-macos-edition.cjs new file mode 100644 index 0000000..0c728c1 --- /dev/null +++ b/scripts/prepare-macos-edition.cjs @@ -0,0 +1,476 @@ +const fs = require('node:fs') +const path = require('node:path') +const { createHash } = require('node:crypto') +const { execFileSync } = require('node:child_process') +const { createGunzip } = require('node:zlib') +const https = require('node:https') +const { pipeline } = require('node:stream/promises') +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_BUNDLE_ROOT = findNativeBundleRoot(NATIVE_DIST_ROOT) +const PUBLIC_FILES = [ + 'icon.png', + 'trayTemplate.png', + 'trayTemplate@2x.png', + 'daily_report_templates.html', + 'mobile_daily_report.html', + 'mobile_daily_report_v1.html', + 'mobile_daily_report_v2.html', + 'xkey_helper', + 'xkey_helper_4_1_13' +] +const FFMPEG_LICENSE_FILES = [ + ['LICENSE', 'licenses/ffmpeg-static/LICENSE'], + ['ffmpeg.LICENSE', 'licenses/ffmpeg-static/FFMPEG-LICENSE.txt'], + ['ffmpeg.README', 'licenses/ffmpeg-static/FFMPEG-BUILD-INFO.txt'] +] +const REQUIRED_NATIVE_SYMBOLS = [ + 'wcdb_msg_insert_set_switch', + 'wcdb_msg_insert_get_switches', + 'wcdb_msg_insert_list_shard_catalog', + 'wcdb_msg_insert_ensure_rooms_rules', + 'wcdb_msg_insert_get_rooms_status', + 'wcdb_msg_insert_inspect_shard', + 'wcdb_msg_insert_insert_local_notice', + 'wcdb_msg_insert_insert_local_notice_ex', + 'wcdb_msg_insert_sync_display_names' +] +const REQUIRED_PUBLIC_SYMBOLS = [ + 'wcdb_get_messages', + 'wcdb_get_group_members_batch', + 'wcdb_start_monitor_pipe' +] +const PROTECTED_RESOURCE_PATHS = ['runtime/runtime.zip'] + +function sha256(filePath) { + return createHash('sha256').update(fs.readFileSync(filePath)).digest('hex') +} + +function resolveWcdbDistRoot() { + const configured = process.env.TRACEMEMO_WCDB_DIST_ROOT + const candidates = [ + configured, + path.resolve(ROOT, '..', 'wcdb-dist', 'build', 'macos-package-universal'), + path.resolve(ROOT, '..', '..', 'workspace', 'wcdb-dist', 'build', 'macos-package-universal') + ].filter(Boolean) + return candidates.find((candidate) => fs.existsSync(candidate)) || candidates[0] +} + +function findNativeBundleRoot(root) { + if (!fs.existsSync(root)) return root + const pending = [{ directory: root, depth: 0 }] + while (pending.length) { + const { directory, depth } = pending.shift() + const manifest = path.join(directory, 'manifest.json') + if (fs.existsSync(manifest)) { + try { + const parsed = JSON.parse(fs.readFileSync(manifest, 'utf8')) + if (parsed.platform === 'macos' && parsed.architecture === 'arm64' && Array.isArray(parsed.files)) { + return directory + } + } catch { + // Ignore unrelated manifests while locating the native runtime bundle. + } + } + 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 }) + } + } + return root +} + +function run(command, args) { + return execFileSync(command, args, { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }) +} + +function binaryArchitectures(filePath) { + return readBinaryArchitectures(filePath) +} + +function exportedSymbols(filePath) { + return run('/usr/bin/nm', ['-gU', filePath]) + .split(/\r?\n/) + .map((line) => line.trim().split(/\s+/).pop()) + .filter(Boolean) + .map((symbol) => symbol.replace(/^_/, '')) +} + +function assertArm64(filePath, label) { + if (!binaryArchitectures(filePath).includes('arm64')) { + throw new Error(`${label} does not contain arm64: ${filePath}`) + } +} + +function validateWcdbPair(apiPath, dependencyPath, profile) { + if (!fs.existsSync(apiPath) || !fs.existsSync(dependencyPath)) { + throw new Error(`Missing ${profile} WCDB library pair: ${apiPath}`) + } + assertArm64(apiPath, `${profile} WCDB API`) + assertArm64(dependencyPath, `${profile} WCDB companion`) + const symbols = exportedSymbols(apiPath) + 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') + } + const dependencies = run('/usr/bin/otool', ['-L', apiPath]) + if (!dependencies.includes('@loader_path/libWCDB.dylib')) { + throw new Error(`${profile} WCDB API does not resolve libWCDB.dylib via @loader_path`) + } +} + +function readAndValidateNativeManifest(bundleRoot) { + const manifestPath = path.join(bundleRoot, 'manifest.json') + const manifest = JSON.parse(fs.readFileSync(manifestPath, 'utf8')) + 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') + } + 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)) { + throw new Error('Native bundle manifest contains an unexpected resource path') + } + if (normalized.has(entry.path) || !/^[a-f0-9]{64}$/.test(entry.sha256 || '')) { + throw new Error(`Invalid native bundle manifest entry: ${String(entry.path)}`) + } + normalized.add(entry.path) + const source = path.join(bundleRoot, entry.path) + const stat = fs.statSync(source) + if (!stat.isFile() || stat.size !== entry.bytes || sha256(source) !== entry.sha256) { + 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 (!binaryArchitectures(source).includes('arm64')) { + throw new Error(`Native runtime binary is not arm64: ${entry.path}`) + } + } + if (/\/wcdb\/(libwcdb_api\.dylib|tm-wcdb-config-helper)$/.test(entry.path)) { + if (!binaryArchitectures(source).includes('arm64')) { + throw new Error(`Native WCDB binary is not arm64: ${entry.path}`) + } + } + } + const expected = [ + 'tracememo/runtime/libtmwechat.dylib', + 'tracememo/runtime/runtime-manifest.json', + 'tracememo/runtime/tm-wechat-host', + 'tracememo/wcdb/libWCDB.dylib', + 'tracememo/wcdb/libwcdb_api.dylib', + 'tracememo/wcdb/tm-wcdb-config-helper' + ] + 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') + return { manifest, files: manifest.files } +} + +function validateNativeBundle(bundleRoot, files) { + const bySuffix = (suffix) => { + const entry = files.find((file) => file.path.endsWith(suffix)) + if (!entry) throw new Error(`Missing native bundle manifest path: ${suffix}`) + return path.join(bundleRoot, entry.path) + } + const api = bySuffix('/wcdb/libwcdb_api.dylib') + const companion = bySuffix('/wcdb/libWCDB.dylib') + const helper = bySuffix('/wcdb/tm-wcdb-config-helper') + const host = bySuffix('/runtime/tm-wechat-host') + const runtimeDylib = bySuffix('/runtime/libtmwechat.dylib') + const runtimeManifestPath = bySuffix('/runtime/runtime-manifest.json') + validateWcdbPair(api, companion, 'native') + for (const [binary, label] of [[helper, 'WCDB helper'], [host, 'WeChat host'], [runtimeDylib, 'WeChat runtime']]) { + assertArm64(binary, label) + } + 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') + } + const bundleManifest = JSON.parse(fs.readFileSync(path.join(bundleRoot, 'manifest.json'), 'utf8')) + const runtimeDependencies = run('/usr/bin/otool', ['-L', runtimeDylib]) + if (!bundleManifest.compatibility || bundleManifest.proWcdbAbiVersion !== 1) { + 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) { + 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) { + 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)) { + 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]))) { + 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 (!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')) { + 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}`) + } +} + +function copyPublicResources(sourceResources, destination) { + for (const relative of PUBLIC_FILES) { + const source = path.join(sourceResources, relative) + if (!fs.existsSync(source)) throw new Error(`Missing public resource: ${source}`) + fs.mkdirSync(path.dirname(path.join(destination, relative)), { recursive: true }) + fs.copyFileSync(source, path.join(destination, relative), fs.constants.COPYFILE_EXCL) + } +} + +function copyFfmpegLicenses(destination) { + const packageRoot = path.dirname(require.resolve('ffmpeg-static/package.json')) + for (const [sourceName, destinationRelative] of FFMPEG_LICENSE_FILES) { + const source = path.join(packageRoot, sourceName) + if (!fs.existsSync(source)) throw new Error(`Missing FFmpeg license/source notice: ${source}`) + const target = path.join(destination, destinationRelative) + fs.mkdirSync(path.dirname(target), { recursive: true }) + fs.copyFileSync(source, target, fs.constants.COPYFILE_EXCL) + } +} + +function copyNative(source, destination) { + fs.mkdirSync(path.dirname(destination), { recursive: true }) + fs.copyFileSync(source, destination, fs.constants.COPYFILE_EXCL) +} + +async function downloadFfmpegArm64(destination) { + 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) + }) + request(url).on('error', reject) + }) + await pipeline(fs.createReadStream(archivePath), createGunzip(), fs.createWriteStream(destination, { flags: 'wx' })) + fs.unlinkSync(archivePath) + fs.chmodSync(destination, 0o755) + assertArm64(destination, 'Staged FFmpeg') +} + +async function prepareFfmpeg(stagedResources) { + const destination = path.join(stagedResources, 'ffmpeg', 'ffmpeg') + fs.mkdirSync(path.dirname(destination), { recursive: true }) + const supplied = process.env.TRACEMEMO_FFMPEG_ARM64_PATH + if (supplied) { + assertArm64(supplied, 'Provided FFmpeg') + copyNative(supplied, destination) + fs.chmodSync(destination, 0o755) + return sha256(destination) + } + await downloadFfmpegArm64(destination) + return sha256(destination) +} + +function assertNoProtectedInputs(root) { + for (const relative of ['1.txt']) { + if (fs.existsSync(path.join(ROOT, relative))) { + throw new Error(`Protected file must not be used as a build input: ${relative}`) + } + } + for (const relative of PROTECTED_RESOURCE_PATHS) { + if (fs.existsSync(path.join(root, relative))) { + throw new Error(`Protected file must not be used as a build input: ${relative}`) + } + } +} + +async function prepareEdition(edition) { + 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) + + const sourceResources = path.join(ROOT, 'resources') + assertNoProtectedInputs(sourceResources) + 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 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) + } + } 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)) + } + 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}`) + } + } + 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 + } +} + +function validateStagedEdition(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) { + 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') + 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') + } + assertArm64(ffmpeg, 'Staged FFmpeg') + const api = path.join(resources, 'wcdb', 'macos', 'arm64', 'libwcdb_api.dylib') + const companion = path.join(resources, 'wcdb', 'macos', 'arm64', 'libWCDB.dylib') + validateWcdbPair(api, companion, edition) + if (marker.nativeInput?.libwcdbApiSha256 && sha256(api) !== marker.nativeInput.libwcdbApiSha256) { + throw new Error('Staged public WCDB API does not match the recorded input hash') + } + if (marker.nativeInput?.libWCDBSha256 && sha256(companion) !== marker.nativeInput.libWCDBSha256) { + throw new Error('Staged public WCDB companion does not match the recorded input hash') + } + 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') + } + 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\//, '')) + const staged = path.join(resources, stagedRelative) + 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) + } + 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}`) + } + 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 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 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']]) { + assertArm64(binary, label) + } + 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) { + 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]))) { + throw new Error(`Staged runtime hash verification failed: ${key}`) + } + } +} + +if (require.main === module) { + try { + 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 + } +} + +module.exports = { + assertNoProtectedInputs, + assertStagingTargetDoesNotExist, + copyPublicResources, + copyFfmpegLicenses, + downloadFfmpegArm64, + prepareFfmpeg, + prepareEdition, + validateNativeBundleFromStaging, + validateStagedEdition, + readAndValidateNativeManifest, + validateNativeBundle, + validateWcdbPair +} diff --git a/src/main/ffmpeg-path.ts b/src/main/ffmpeg-path.ts new file mode 100644 index 0000000..667ed45 --- /dev/null +++ b/src/main/ffmpeg-path.ts @@ -0,0 +1,12 @@ +import { app } from 'electron' +import fs from 'node:fs' +import path from 'node:path' +import ffmpegStaticPath from 'ffmpeg-static' + +export function resolveBundledFfmpegPath(): string { + if (process.platform === 'darwin' && app.isPackaged) { + const editionFfmpeg = path.join(process.resourcesPath, 'resources', 'ffmpeg', 'ffmpeg') + if (fs.existsSync(editionFfmpeg)) return editionFfmpeg + } + return String(ffmpegStaticPath || '').replace('app.asar', 'app.asar.unpacked').trim() +} diff --git a/src/main/image-decrypt-service.ts b/src/main/image-decrypt-service.ts index e738281..c21a00e 100644 --- a/src/main/image-decrypt-service.ts +++ b/src/main/image-decrypt-service.ts @@ -5,7 +5,7 @@ import os from 'os' import { app } from 'electron' import { execFile } from 'child_process' import { Worker } from 'worker_threads' -import ffmpegStaticPath from 'ffmpeg-static' +import { resolveBundledFfmpegPath } from './ffmpeg-path' import type { ImageDecoderSource, ImageDecoderStatus } from '../shared/image-decryption' import { imageFileQuality, imageQualityRank } from '../shared/image-quality' import { loadSettings } from './services/settings-store' @@ -78,9 +78,7 @@ function getFfmpegCandidates(selectedPath = loadSettings().ffmpegPath): FfmpegCa const selected = String(selectedPath || '').trim() const environment = String(process.env['FFMPEG_BIN'] || '').trim() const executable = process.platform === 'win32' ? 'ffmpeg.exe' : 'ffmpeg' - const staticExecutable = String(ffmpegStaticPath || '') - .replace('app.asar', 'app.asar.unpacked') - .trim() + const staticExecutable = resolveBundledFfmpegPath() const candidates: FfmpegCandidate[] = [ ...(selected ? [{ executable: selected, source: 'selected' as const }] : []), ...(environment ? [{ executable: environment, source: 'environment' as const }] : []), diff --git a/src/main/index.ts b/src/main/index.ts index f1a2f5a..5454603 100644 --- a/src/main/index.ts +++ b/src/main/index.ts @@ -202,6 +202,7 @@ function buildMsgInsertSwitchesSnapshot(): MsgInsertSwitchesSnapshot { const scope = resolveMsgInsertScopeInput() if (scope) { const snapshot = readMsgInsertSwitches(scope) + snapshot.sendCapabilityAvailable = !isMacNativeRuntimeUnavailable() /* 退群提示的开关状态来自本地设置(事件驱动,不装规则), * 不是微信库里的 _tm_config。 */ snapshot.switches.group_exit_notice = eventModeStatus( @@ -213,6 +214,7 @@ function buildMsgInsertSwitchesSnapshot(): MsgInsertSwitchesSnapshot { } return { success: false, + sendCapabilityAvailable: !isMacNativeRuntimeUnavailable(), switches: { recall_notice: emptyMsgInsertStatus('recall_notice'), group_exit_notice: eventModeStatus( @@ -390,6 +392,7 @@ import type { PersonalWechatSendResult, PersonalWechatSenderStatus } from '../shared/personal-wechat' +import { isMacNativeRuntimeUnavailable } from './native-runtime-paths' import { isTruthyDebugFlag } from '../shared/debug-flags' import { TextToSpeechSettingsService } from './services/text-to-speech-settings-service' import type { @@ -2252,6 +2255,14 @@ app.whenReady().then(async () => { message: '未知的开关' } } + if (isMacNativeRuntimeUnavailable()) { + return { + success: false, + status: emptyMsgInsertStatus(name, 'HELPER_NOT_FOUND', '微信内消息插入仅在 TraceMemo 具备发送能力时开放'), + errorCode: 'HELPER_NOT_FOUND', + message: '微信内防撤回与退群消息插入仅在 TraceMemo 具备发送能力时开放;退群检测和历史记录不受影响' + } + } /* * 退群提示是**事件驱动**的(GroupExitMonitorService 发事件 → 一次性插一条), * 不装任何 per-room 规则。所以它的开关只是本地设置: diff --git a/src/main/native-runtime-paths.ts b/src/main/native-runtime-paths.ts new file mode 100644 index 0000000..d15e02d --- /dev/null +++ b/src/main/native-runtime-paths.ts @@ -0,0 +1,90 @@ +import fs from 'node:fs' +import path from 'node:path' +import { app } from 'electron' + +import { findResource } from './resource-paths' + +export type NativeRuntimeProfile = 'public' | 'native' + +const BUILD_MARKER = 'tracememo-build.json' +const RUNTIME_RELATIVE = 'runtime/darwin-arm64' + +let cachedProfile: NativeRuntimeProfile | null = null +let cachedMarkerRead = false + +function getNativeRuntimeProfile(): NativeRuntimeProfile { + const envProfile = !app.isPackaged ? process.env.TRACEMEMO_RUNTIME_PROFILE : undefined + if (envProfile === 'public' || envProfile === 'native') return envProfile + if (cachedMarkerRead && cachedProfile) return cachedProfile + cachedMarkerRead = true + const marker = findResource(BUILD_MARKER) + if (marker) { + try { + const parsed = JSON.parse(fs.readFileSync(marker, 'utf8')) as { profile?: unknown } + if (parsed.profile === 'public' || parsed.profile === 'native') { + cachedProfile = app.isPackaged ? parsed.profile : 'native' + return cachedProfile + } + } catch { + // Packaged builds fail closed below when the marker cannot be read. + } + } + cachedProfile = app.isPackaged ? 'public' : 'native' + return cachedProfile +} + +export function hasMacNativeBundle(): boolean { + return process.platform === 'darwin' && getNativeRuntimeProfile() === 'native' +} + +export function isMacNativeRuntimeUnavailable(): boolean { + return process.platform === 'darwin' && !hasMacNativeBundle() +} + +export function resolveWcdbLibrary(): string | null { + if (process.platform !== 'darwin') return null + const arch = process.arch === 'arm64' ? 'arm64' : 'x64' + return findResource(`wcdb/macos/${arch}/libwcdb_api.dylib`) +} + +export function resolveWcdbDependency(): string | null { + const library = resolveWcdbLibrary() + if (!library) return null + const dependency = path.join(path.dirname(library), 'libWCDB.dylib') + return fs.existsSync(dependency) ? dependency : null +} + +export function resolveWcdbConfigHelper(): string | null { + if (isMacNativeRuntimeUnavailable()) return null + const arch = process.arch === 'arm64' ? 'arm64' : 'x64' + return findResource(`wcdb/macos/${arch}/tm-wcdb-config-helper`) +} + +export function resolveWechatRuntimeDirectory(): string | null { + if (!hasMacNativeBundle()) return null + const manifest = + findResource(`${RUNTIME_RELATIVE}/runtime-manifest.json`) || + (!app.isPackaged ? findResource('runtime/darwin-arm64/runtime-manifest.json') : null) + return manifest ? path.dirname(manifest) : null +} + +export function resolveWechatHost(): string | null { + const directory = resolveWechatRuntimeDirectory() + if (!directory) return null + const candidate = path.join(directory, 'tm-wechat-host') + return fs.existsSync(candidate) ? candidate : null +} + +export function resolveWechatDylib(): string | null { + const directory = resolveWechatRuntimeDirectory() + if (!directory) return null + const candidate = path.join(directory, 'libtmwechat.dylib') + return fs.existsSync(candidate) ? candidate : null +} + +export function resolveWechatRuntimeManifest(): string | null { + const directory = resolveWechatRuntimeDirectory() + if (!directory) return null + const candidate = path.join(directory, 'runtime-manifest.json') + return fs.existsSync(candidate) ? candidate : null +} diff --git a/src/main/resource-paths.ts b/src/main/resource-paths.ts index d31128c..77e621e 100644 --- a/src/main/resource-paths.ts +++ b/src/main/resource-paths.ts @@ -7,6 +7,10 @@ function unique(values: string[]): string[] { } export function getResourceRoots(): string[] { + if (app.isPackaged && process.platform === 'darwin') { + const packagedResources = join(process.resourcesPath || '', 'resources') + return existsSync(packagedResources) ? [packagedResources] : [] + } const appPath = app.getAppPath() const appPathDir = dirname(appPath) const execDir = dirname(process.execPath) diff --git a/src/main/services/mac-wechat-runtime-manager.ts b/src/main/services/mac-wechat-runtime-manager.ts index 4ab19dc..0ac3048 100644 --- a/src/main/services/mac-wechat-runtime-manager.ts +++ b/src/main/services/mac-wechat-runtime-manager.ts @@ -6,7 +6,7 @@ import { join } from 'path' import { app } from 'electron' import { appLogger } from '../app-logger' -import { isPackagedRuntime } from '../runtime-mode' +import { isMacNativeRuntimeUnavailable, resolveWechatRuntimeDirectory } from '../native-runtime-paths' import type { MacWechatBindResult, MacWechatBindingStatus, @@ -180,25 +180,31 @@ class MacWechatRuntimeManager { wechatRestartRequired: this.wechatRestartRequired, endpoint: `http://${HOST}:${PORT}`, port: PORT, - runtimeDir: this.resolveRuntimeDir(), + runtimeDir: this.resolveRuntimeDir() ?? undefined, error: this.lastError ?? undefined, binding: this.lastBinding ?? undefined } } - private resolveRuntimeDir(): string { - const base = isPackagedRuntime() ? process.resourcesPath : app.getAppPath() - return join(base, 'resources', 'runtime', 'darwin-arm64') + private resolveRuntimeDir(): string | null { + if (isMacNativeRuntimeUnavailable()) return null + const resolved = resolveWechatRuntimeDirectory() + if (resolved) return resolved + if (app.isPackaged) return null + return join(app.getAppPath(), 'resources', 'runtime', 'darwin-arm64') } private resolveHostPath(): string { - return join(this.resolveRuntimeDir(), 'tm-wechat-host') + return join(this.resolveRuntimeDir() || '', 'tm-wechat-host') } /** Runtime binaries present and executable? Cheap check for the settings UI. */ isRuntimePresent(): boolean { + if (isMacNativeRuntimeUnavailable()) return false try { - this.manifest = readMacWechatRuntimeManifest(this.resolveRuntimeDir()) + const runtimeDir = this.resolveRuntimeDir() + if (!runtimeDir) return false + this.manifest = readMacWechatRuntimeManifest(runtimeDir) return true } catch { return false @@ -211,11 +217,22 @@ class MacWechatRuntimeManager { * online" and "WeChat bound" stay two independent states. */ async ensureStarted(): Promise { + if (isMacNativeRuntimeUnavailable()) { + this.manifest = null + this.lifecycle = 'stopped' + this.lastError = '当前环境不包含微信发送能力' + return this.getSnapshot() + } if (this.lifecycle === 'starting') { return this.getSnapshot() } const runtimeDir = this.resolveRuntimeDir() + if (!runtimeDir) { + this.lifecycle = 'stopped' + this.lastError = '暂无发送能力' + return this.getSnapshot() + } try { this.manifest = readMacWechatRuntimeManifest(runtimeDir) appLogger.write({ @@ -517,6 +534,32 @@ class MacWechatRuntimeManager { * circular import. */ async buildSenderStatus(): Promise { + if (isMacNativeRuntimeUnavailable()) { + const message = '当前环境不包含微信发送能力' + return { + state: 'runtime_missing', + platform: 'darwin', + arch: process.arch, + sipDisabled: true, + wechatRunning: false, + endpoint: `http://${HOST}:${PORT}`, + 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, + error: message + } + } /* * Lazy-start the host from status reads. * @@ -534,7 +577,9 @@ class MacWechatRuntimeManager { /* Self-heal the status card too: if WeChat was restarted, drop the stale * restartRequired before it is read into the UI as an error. */ try { - this.manifest = readMacWechatRuntimeManifest(this.resolveRuntimeDir()) + const runtimeDir = this.resolveRuntimeDir() + if (!runtimeDir) throw new Error('runtime missing') + this.manifest = readMacWechatRuntimeManifest(runtimeDir) } catch (error) { const detail = error instanceof Error ? error.message : String(error) appLogger.write({ @@ -605,6 +650,14 @@ class MacWechatRuntimeManager { * live WeChat pid again returns attached=false and never double-attaches. */ async bind(): Promise { + if (isMacNativeRuntimeUnavailable()) { + return { + ok: false, + attached: false, + state: 'runtime_offline', + message: '当前环境不包含微信发送能力' + } + } if (this.lifecycle !== 'online') { const snapshot = await this.ensureStarted() if (snapshot.lifecycle !== 'online') { @@ -687,6 +740,7 @@ class MacWechatRuntimeManager { * leave its injected agent inside WeChat and make the next attach hang. */ async shutdown(): Promise { + if (isMacNativeRuntimeUnavailable()) return if (this.restartTimer) { clearTimeout(this.restartTimer) this.restartTimer = null diff --git a/src/main/services/msg-insert-switch-service.ts b/src/main/services/msg-insert-switch-service.ts index 21882d9..9e10813 100644 --- a/src/main/services/msg-insert-switch-service.ts +++ b/src/main/services/msg-insert-switch-service.ts @@ -29,6 +29,7 @@ import { createHash } from 'node:crypto' import path from 'node:path' import { findResource } from '../resource-paths' +import { isMacNativeRuntimeUnavailable, resolveWcdbConfigHelper } from '../native-runtime-paths' import type { Wcdb4Client } from '../wcdb4-client' import { MSG_INSERT_SWITCHES, @@ -156,6 +157,7 @@ export function emptyMsgInsertStatus( * 开发态与打包态都靠 findResource 解析,不依赖当前工作目录。 */ export function resolveHelperPath(): string | null { + if (process.platform === 'darwin') return resolveWcdbConfigHelper() /* * 平台/架构都要分。Windows 交付在 `resources/wcdb/win32/x64/`(注意是 win32 不是 windows), * 文件名带 `.exe`。以前这里三个候选全写死 macos —— Windows 上会恒返回 null, @@ -640,6 +642,14 @@ export async function applyMsgInsertSwitch( } } + if (isMacNativeRuntimeUnavailable()) { + return { + success: false, + status: emptyMsgInsertStatus(input.name, 'HELPER_NOT_FOUND', '微信内消息插入仅在 TraceMemo 具备发送能力时开放'), + errorCode: 'HELPER_NOT_FOUND', + message: '微信内防撤回与退群消息插入仅在 TraceMemo 具备发送能力时开放;退群检测和历史记录不受影响' + } + } const helperPath = resolveHelperPath() if (!helperPath) { return { @@ -716,6 +726,9 @@ export async function applyMsgInsertSwitch( export async function reconcileMsgInsertRules( input: MsgInsertScopeInput & { myWxid: string; databaseKey: string; extraRooms?: string[] } ): Promise<{ done: boolean; rooms: number; written: number; errorCode?: MsgInsertErrorCode }> { + if (isMacNativeRuntimeUnavailable()) { + return { done: false, rooms: 0, written: 0, errorCode: 'HELPER_NOT_FOUND' } + } const helperPath = resolveHelperPath() if (!helperPath || !input.databaseKey) { return { diff --git a/src/main/services/personal-wechat-send-service.ts b/src/main/services/personal-wechat-send-service.ts index 57749d2..7fc7e1a 100644 --- a/src/main/services/personal-wechat-send-service.ts +++ b/src/main/services/personal-wechat-send-service.ts @@ -12,7 +12,7 @@ import { } from 'fs' import { homedir, tmpdir } from 'os' import { delimiter, dirname, extname, join, sep } from 'path' -import ffmpegStaticPath from 'ffmpeg-static' +import { resolveBundledFfmpegPath } from '../ffmpeg-path' import { promisify } from 'util' import type { PersonalWechatSendRequest, @@ -64,9 +64,7 @@ function windowsHookHost(port?: unknown): string | null { export function buildPersonalWechatRuntimePath(): string { const existing = String(process.env['PATH'] || '') - const bundledFfmpeg = String(ffmpegStaticPath || '') - .replace('app.asar', 'app.asar.unpacked') - .trim() + const bundledFfmpeg = resolveBundledFfmpegPath() if (!bundledFfmpeg || !existsSync(bundledFfmpeg)) return existing return [dirname(bundledFfmpeg), existing].filter(Boolean).join(delimiter) } @@ -174,7 +172,7 @@ async function detectVoiceDurationMs(filePath: string): Promise { const fromEnvironment = String(process.env['FFMPEG_BIN'] || '').trim() if (fromEnvironment) return fromEnvironment try { - const bundled = require('ffmpeg-static') as string | null + const bundled = resolveBundledFfmpegPath() if (bundled) return bundled } catch { // 忽略:退回到 PATH 上的 ffmpeg diff --git a/src/main/services/wechat-local-exit-notice-service.ts b/src/main/services/wechat-local-exit-notice-service.ts index 0480d8f..89baa80 100644 --- a/src/main/services/wechat-local-exit-notice-service.ts +++ b/src/main/services/wechat-local-exit-notice-service.ts @@ -34,6 +34,7 @@ import type { GroupMemberExitedEvent } from '../../shared/group-exit-event' import { renderLeaveNotificationText } from '../../shared/group-exit-event' import { GROUP_EXIT_NOTIFICATION_TEMPLATE } from '../../shared/group-exit-monitor' import { findResource } from '../resource-paths' +import { isMacNativeRuntimeUnavailable, resolveWcdbConfigHelper } from '../native-runtime-paths' export type LocalExitNoticeOutcome = | 'inserted' @@ -63,6 +64,7 @@ const HELPER_TIMEOUT_MS = 20_000 const RECENT_LIMIT = 50 function helperPath(): string | null { + if (process.platform === 'darwin') return resolveWcdbConfigHelper() /* 与 msg-insert-switch-service 的 resolveHelperPath 保持一致: * Windows 走 wcdb/win32// 且文件名带 .exe。 */ const arch = process.arch === 'x64' ? 'x64' : 'arm64' @@ -149,6 +151,9 @@ export class WechatLocalExitNoticeService { } try { this.ensureLoaded() + if (isMacNativeRuntimeUnavailable()) { + return this.finish({ ...base, outcome: 'disabled', code: 'SEND_CAPABILITY_UNAVAILABLE' }) + } if (!this.enabled) return this.finish({ ...base, outcome: 'disabled', code: 'DISABLED' }) if (!event.eventId || !event.conversationId) { return this.finish({ ...base, outcome: 'failed', code: 'EVENT_INCOMPLETE' }) diff --git a/src/main/wcdb4-client.ts b/src/main/wcdb4-client.ts index c1ed2c0..3b844b0 100644 --- a/src/main/wcdb4-client.ts +++ b/src/main/wcdb4-client.ts @@ -5,6 +5,7 @@ import crypto from 'crypto' import { createRequire } from 'module' import { createConnection, Socket } from 'net' import { getResourceRoots } from './resource-paths' +import { resolveWcdbLibrary } from './native-runtime-paths' import { wcdbDebugLog } from './wcdb-debug' import { looksLikePermissionDenied, PathAccessDeniedError } from './services/path-access-probe' import type { ImageMessageCountProbe } from '../shared/image-text-index' @@ -3485,16 +3486,14 @@ export class Wcdb4Client { } static resolveNativeLibrary(): string { - const libName = - process.platform === 'darwin' - ? 'libwcdb_api.dylib' - : process.platform === 'linux' - ? 'libwcdb_api.so' - : 'wcdb_api.dll' + if (process.platform === 'darwin') { + const library = resolveWcdbLibrary() + if (library) return library + throw new Error('找不到当前发行版对应的 WCDB native 库') + } + const libName = process.platform === 'linux' ? 'libwcdb_api.so' : 'wcdb_api.dll' const platformDir = - process.platform === 'darwin' - ? 'macos' - : process.platform === 'win32' + process.platform === 'win32' ? 'win32' : process.platform const archDir = process.arch === 'arm64' ? 'arm64' : 'x64' diff --git a/src/renderer/src/features/automation/MessageInsertSwitches.tsx b/src/renderer/src/features/automation/MessageInsertSwitches.tsx index 2e70b39..9a816e4 100644 --- a/src/renderer/src/features/automation/MessageInsertSwitches.tsx +++ b/src/renderer/src/features/automation/MessageInsertSwitches.tsx @@ -174,25 +174,17 @@ export function MessageInsertSwitches(): React.JSX.Element { [humanize, pending, refresh, toast] ) - /* - * helper 缺失时**提前**禁用,而不是等用户点了再弹「缺少写入组件」。 - * 写开关必须靠那个一次性子进程,缺了它这个开关根本没法工作 —— - * 让人点了才失败是最差的一种交互。 - */ - /* - * 写入组件缺失 = **这个能力还没开放**,不是安装坏了。 - * - * 主进程对微信库只有只读连接,任何写入都要 spawn 那个一次性写入组件;当前分发的 - * 安装包不带它(它随发送运行时按需分发),所以「微信内防撤回提示」与 - * 「微信内退群监控消息」一律按"下个版本开放"呈现 —— 不该让用户去排查自己的安装。 - * (machine-readable 的原因仍然是 snapshot.helperAvailable,授权层可以据此判断。) - */ + /* 微信内消息插入必须依赖可用的发送组件;能力状态由主进程统一判定。 */ const helperMissing = snapshot?.helperAvailable === false - const blocked = blockedReason ?? (helperMissing ? '该能力将在下个版本开放' : null) + const capabilityNotice = snapshot?.sendCapabilityAvailable === false + ? '微信内防撤回与退群消息插入仅在 TraceMemo 具备发送能力时开放;退群检测和历史记录不受影响' + : null + const blocked = capabilityNotice ?? blockedReason ?? (helperMissing ? '该能力暂不可用' : null) const disabled = blocked !== null return (
+ {capabilityNotice ?

{capabilityNotice}

: null} {loading ? : null} {MSG_INSERT_SWITCH_LABELS.map(({ name, label, hint }) => { const status: MsgInsertSwitchStatus | undefined = snapshot?.switches?.[name] diff --git a/src/shared/msg-insert-switch.ts b/src/shared/msg-insert-switch.ts index 62a9cbd..5a14d6e 100644 --- a/src/shared/msg-insert-switch.ts +++ b/src/shared/msg-insert-switch.ts @@ -106,10 +106,11 @@ export interface MsgInsertSwitchStatus { export interface MsgInsertSwitchesSnapshot { success: boolean + sendCapabilityAvailable?: boolean switches: Record - /** helper 是否可用(不可用时只能读不能写) */ + /** 写入组件是否可用(不可用时只能读不能写) */ /** - * **能力标志**:本机是否存在「微信内消息写入组件」(那个一次性 helper)。 + * **能力标志**:本机是否存在「微信内消息写入组件」。 * * 这是「微信内防撤回提示」和「微信内退群监控消息」的**唯一硬门槛**: * 主进程对微信库只持只读连接,任何写入都必须 spawn 那个组件,没有它两个功能都做不了。 @@ -117,9 +118,7 @@ export interface MsgInsertSwitchesSnapshot { * 语义上它是 **capability(能力)**,不是 error(错误)—— * 缺失时 UI 显示「暂无法使用」,而不是「请重新安装」。 * - * ⚠️ 它是**唯一**的能力判据,不要再新增第二份(曾经因为 native 与 TS 各存一份判据 - * 而出现 946 里莫名少 323 的假象)。将来的授权/付费门禁应当**并列**加在它旁边 - * (capability && entitlement),而不是替换它。 + * 它是组件能力判据;授权状态应与其并列,不能替换它。 */ helperAvailable: boolean /** native code 只放这里,不往 UI 上抛 */ diff --git a/tests/unit/runtime-packaging.test.ts b/tests/unit/runtime-packaging.test.ts index 0c74237..9aa3830 100644 --- a/tests/unit/runtime-packaging.test.ts +++ b/tests/unit/runtime-packaging.test.ts @@ -19,6 +19,19 @@ const asar = nodeRequire('@electron/asar') as { const { hasWindowsSherpaRuntime } = nodeRequire('../../scripts/prepare-win-runtime.cjs') as { hasWindowsSherpaRuntime: (runtimeRoot: string) => boolean } +const { createBuilderConfig } = nodeRequire('../../scripts/build-macos-edition.cjs') as { + createBuilderConfig: (options: { + edition: 'public' | 'native' + stageRoot: string + buildOutput: string + outputRoot: string + appVersion: string + }) => { + files: Array + extraResources: Array<{ from: string; to: string }> + dmg: { artifactName: string } + } +} const { validateAsarRuntimeDependencies, validateFfmpegRuntime, @@ -32,7 +45,11 @@ const { signMacosAppBundle } = nodeRequire('../../scripts/after-pack.cjs') as { validateAsarRuntimeDependencies: (runtimeResources: string) => void - validateFfmpegRuntime: (runtimeResources: string, platform?: NodeJS.Platform) => void + validateFfmpegRuntime: ( + runtimeResources: string, + platform?: NodeJS.Platform, + edition?: string + ) => string validateKoffiRuntime: (runtimeResources: string, platform: NodeJS.Platform, arch: string) => void validateReaderSkillRuntime: (runtimeResources: string) => string validateSherpaRuntime: (runtimeResources: string, platform: NodeJS.Platform, arch: string) => void @@ -246,6 +263,48 @@ describe('production runtime packaging', () => { expect(config).toContain('node_modules/ffmpeg-static/**') }) + it('requires staged arm64 edition ffmpeg before removing the shared binary', () => { + const resources = join(root, 'edition-ffmpeg-resources') + const shared = join(resources, 'app.asar.unpacked', 'node_modules', 'ffmpeg-static', 'ffmpeg') + mkdirSync(dirname(shared), { recursive: true }) + writeFileSync(shared, 'existing shared binary') + expect(() => validateFfmpegRuntime(resources, 'darwin', 'public')).toThrow(/staged macOS ffmpeg/) + expect(readFileSync(shared, 'utf8')).toBe('existing shared binary') + }) + + it('builds each edition from an isolated native resource allowlist', () => { + const stageRoot = join(root, 'mac-staging', 'public') + const config = createBuilderConfig({ + edition: 'public', + stageRoot, + buildOutput: join(stageRoot, 'out'), + outputRoot: join(root, 'dist', 'mac', 'public'), + appVersion: '2.5.2' + }) + expect(config.extraResources.map((item) => item.to)).toEqual([ + 'resources', + 'app-update.yml', + 'skill/tracememo-reader' + ]) + expect(config.extraResources[0].from).toBe(join(stageRoot, 'resources')) + expect(config.files).toContainEqual({ from: join(stageRoot, 'out'), to: 'out', filter: ['**/*'] }) + expect(config.files).toContain('package.json') + expect( + config.files.some( + (item) => typeof item === 'string' && !item.startsWith('!') && item.includes('resources') + ) + ).toBe(false) + expect(config.dmg.artifactName).toBe('TraceMemo-2.5.2-mac-arm64-public.dmg') + const nativeConfig = createBuilderConfig({ + edition: 'native', + stageRoot: join(root, 'mac-staging', 'native'), + buildOutput: join(root, 'mac-staging', 'native', 'out'), + outputRoot: join(root, 'dist', 'mac', 'native'), + appVersion: '2.5.2' + }) + expect(nativeConfig.dmg.artifactName).toBe('TraceMemo-2.5.2-mac-arm64-native.dmg') + }) + it('requires the matching Windows and macOS sherpa native runtime', () => { const resources = join(root, 'sherpa-resources') const unpacked = join(resources, 'app.asar.unpacked', 'node_modules')