Fat binary在macOS的签名与公证流程
解读
面试官抛出该题,表面问的是“签名+公证”,实则想验证候选人是否真正踩过“Flutter 桌面/macOS 发版”的坑。国内大厂做跨端桌面产品时,常把 Flutter 模块编译成 fat binary(x86_64+arm64),再打包成 .app 或 .dmg 上架官网或企业内网分发。若签名、公证步骤出错,用户首次打开会弹“无法验证开发者”或“镜像已损坏”,直接劝退。因此,候选人必须能把“codesign + productbuild + notarytool”这一整条链路讲清楚,并说明 Dart/Flutter 构建产物与普通 macOS App 的差异点(例如 Flutter 引擎、各架构插件、资源 bundle 的签名顺序)。答得越深,越能体现“我不仅写 Dart,还真正交付过桌面安装包”。
知识点
- fat binary 概念:单文件内含多架构 slice,Flutter 的
flutter build macos --release默认输出 x86_64+arm64 的 App.framework、FlutterMacOS.framework 以及最终的可执行文件。 - 签名三要素:证书(Developer ID Application)、entitlements、timestamp。
- 签名顺序:先签嵌套最深的 .framework、.dylib,再签主可执行文件,最后签外层 .app,确保每级哈希值向上传递。
- 公证(Notarization):把 .app 打成 zip 或 dmg,上传 Apple 服务器做恶意代码扫描,返回 ticket 后 staple 到本地,实现离线首次启动不弹警告。
- 国内网络加速:使用
notarytool --apple-id --team-id --provider并配置阿里云代理或公司出口白名单,解决上传超时。 - 自动化脚本:用 Dart 写
tool/sign.dart,调用Process.run串行执行codesign --verify --deep --strict、xcrun stapler validate,CI(GitHub Actions/私有 GitLab)里跑完直接产出 .dmg。 - 常见失败:
- 插件带了自己编译的 arm64 .dylib,忘记一起签名,导致架构校验失败;
- entitlements 里声明了
com.apple.security.network.server却未说明用途,公证人工审核被拒; - 使用旧版
altool上传,Apple 已下线,需改用notarytool。
答案
以 Flutter 生成的 macOS fat binary 为例,完整流程分五步:
-
准备证书
在 Xcode → Accounts → Manage Certificates 生成 “Developer ID Application” 证书,导出 p12 并导入到 CI 的 keychain;同时创建macos/Runner/Release.entitlements,最小权限原则,只保留com.apple.security.network.client与com.apple.security.files.user-selected.read-write。 -
逐层签名
用codesign递归签名,顺序不能乱:
a) 对build/macos/Build/Products/Release/FlutterMacOS.framework/Versions/A/FlutterMacOS执行
codesign --force --sign "Developer ID Application: YourCorp (TeamID)" --timestamp --options runtime FlutterMacOS
b) 同理签 App.framework、各插件 .framework 及任何第三方 .dylib。
c) 最后签外层 .app:
codesign --force --sign "Developer ID Application: YourCorp (TeamID)" --timestamp --options runtime --entitlements Release.entitlements Runner.app
d) 验证:codesign --verify --deep --strict --verbose=2 Runner.app,输出valid on disk和satisfies its Designated Requirement即通过。 -
打包
使用create-dmg或hdiutil把 Runner.app 做成只读压缩镜像:
hdiutil create -volname "MyProduct" -srcfolder Runner.app -ov -format UDZO MyProduct.dmg -
公证
国内网络下优先使用notarytool:
xcrun notarytool submit MyProduct.dmg --apple-id ci@yourcorp.com --team-id ABCD123456 --provider YourCorpProvider --wait
成功后会打印Accepted,随后把 ticket staple 到 dmg:
xcrun stapler staple MyProduct.dmg
验证:spctl -a -t open --context context:primary-signature MyProduct.dmg,返回accepted即完成。 -
发布
将已签名+公证的 MyProduct.dmg 上传到阿里云 OSS 或公司官网,用户下载后首次打开不再弹“无法验证开发者”,可正常进入 Flutter 桌面应用。
拓展思考
- 若产品需发布到 Mac App Store,证书要换成 “Mac App Distribution”,签名参数需加
--entitlements AppStore.entitlements并关闭--options runtime,公证步骤改为上传至 App Store Connect,走苹果审核而非 Notarization。 - 对于持续交付,可用 Dart 写一个
sign_cli包:通过package:args解析参数,内部调用Process.start做并发签名,利用Isolate.run把大文件切片并行哈希,提速 30% 以上;再把结果回写至 GitLab MR 评论,实现“签名报告即代码”。 - 未来 Apple 强制要求 “Developer ID” 证书必须启用双重认证并绑定安全密钥,CI 需改用
--keychain-profile把凭据存在专用 keychain,并定期轮换,避免证书泄露导致 fat binary 被恶意重签名。