MacOS 应用公证(不上架 App Store 的情况)
概述
macOS 应用公证(Notarization)是苹果对不在 App Store 分发的应用的强制安全审核流程。未公证的应用在用户安装时会弹出安全警告,影响用户体验。本节介绍两种公证方式:手动公证和使用 electron-notarize 自动公证。
公证的作用
- 消除 macOS Gatekeeper 的"未验证开发者"警告
- 确保应用未被恶意篡改
- 提升用户信任度,降低安装门槛
| 对比项 | App Store 分发 | 独立分发(DMG/PKG) |
|---|---|---|
| 公证方式 | 自动处理 | 需手动公证 |
| 审核流程 | App Store 审核 + 公证 | 仅公证 |
| 分发渠道 | App Store | 官网 / GitHub Releases |
手动公证流程
1. 准备工作
- Apple Developer 账号
- Developer ID Application 证书(
.p12文件) - App-specific Password(从 appleid.apple.com 生成)
2. 配置环境变量
# .env 或 CI 环境变量
export APPLE_ID="your-apple-id@email.com"
export APPLE_PASSWORD="xxxx-xxxx-xxxx-xxxx" # App-specific password
export APPLE_TEAM_ID="XXXXXXXXXX"
export CSC_LINK="/path/to/certificate.p12" # P12 证书绝对路径
export CSC_KEY_PASSWORD="certificate-password" # P12 密码
bash
3. 手动公证命令
# 提交公证请求
xcrun notarytool submit "app-name.dmg" \
--apple-id "$APPLE_ID" \
--password "$APPLE_PASSWORD" \
--team-id "$APPLE_TEAM_ID" \
--wait
# 检查公证状态
xcrun notarytool info <submission-id> \
--apple-id "$APPLE_ID" \
--password "$APPLE_PASSWORD" \
--team-id "$APPLE_TEAM_ID"
# 公证成功后装订票据
xcrun stapler staple "app-name.dmg"
bash
4. 公证成功标志
- 终端输出
status: Accepted - 收到 Apple 发送的公证成功邮件
stapler staple命令执行成功
使用 electron-notarize 自动公证
安装依赖
npm install electron-notarize --save-dev
bash
配置 afterSign 钩子
// build/notarize.js
const { notarize } = require('electron-notarize')
exports.default = async function notarizing(context) {
const { electronPlatformName, appOutDir } = context
if (electronPlatformName !== 'darwin') return
const appName = context.packager.appInfo.productFilename
return await notarize({
appBundleId: 'com.yourcompany.yourapp',
appPath: `${appOutDir}/${appName}.app`,
appleId: process.env.APPLE_ID,
appleIdPassword: process.env.APPLE_PASSWORD,
teamId: process.env.APPLE_TEAM_ID,
})
}
javascript
electron-builder 配置
{
"build": {
"afterSign": "build/notarize.js",
"mac": {
"hardenedRuntime": true,
"gatekeeperAssess": false,
"entitlements": "build/entitlements.mac.plist",
"entitlementsInherit": "build/entitlements.mac.inherit.plist"
}
}
}
json
公证流程对比
| 步骤 | 手动公证 | electron-notarize |
|---|---|---|
| 提交时机 | 打包后手动执行 | afterSign 钩子自动触发 |
| 命令行操作 | 多条 xcrun 命令 | 一条 npm run build |
| CI/CD 集成 | 需额外脚本 | 原生支持 |
| 出错排查 | 直接查看终端日志 | 需检查钩子输出 |
关键要点
- 不上架 App Store 的应用必须公证,否则用户安装时会遇到安全警告
afterSign钩子在应用签名完成后执行,是公证的最佳时机- 环境变量中
CSC_LINK必须是 P12 证书的绝对路径 hardenedRuntime: true是公证的前置要求- 建议优先使用
electron-notarize自动化方案,避免手动操作遗漏
↑