首页
/ Electron Forge 中 macOS 应用签名与权限配置指南

Electron Forge 中 macOS 应用签名与权限配置指南

2025-06-01 17:50:50作者:郜逊炳

问题背景

在使用 Electron Forge 打包 macOS 应用时,开发者经常会遇到应用签名和权限配置的问题。特别是在需要访问系统资源(如麦克风、摄像头等)时,正确的权限配置尤为重要。

常见错误分析

许多开发者在配置 entitlements.plist 文件时会遇到以下典型错误:

  1. 签名失败:错误提示"code has no resources but signature indicates they must be present"
  2. 权限请求不生效:应用打包后无法正确请求麦克风等权限
  3. 不同进程权限不一致:主进程和辅助进程权限配置不匹配

解决方案详解

1. 分进程配置权限

Electron 应用在 macOS 上运行时包含多个进程,每个进程需要不同的权限配置:

  • 主应用进程 (MyApp.app)
  • GPU 辅助进程 (MyApp Helper (GPU).app)
  • 插件辅助进程 (MyApp Helper (Plugin).app)
  • 渲染器辅助进程 (MyApp Helper (Renderer).app)
  • 通用辅助进程 (MyApp Helper.app)

2. 配置文件示例

以下是推荐的 forge.config.ts 配置:

osxSign: {
  optionsForFile: (filePath) => {
    if (filePath.endsWith('MyApp.app')) {
      return {
        entitlements: path.resolve(__dirname, './entitlements.plist'),
        hardenedRuntime: true,
      }
    }
    if (filePath.endsWith('MyApp Helper (GPU).app')) {
      return {
        entitlements: path.resolve(__dirname, './entitlements.gpu.plist'),
        hardenedRuntime: true,
      }
    }
    // 其他进程配置...
    return {
      entitlements: path.resolve(__dirname, './entitlements.plist'),
      hardenedRuntime: true,
    }
  },
}

3. 各进程权限文件配置

主进程权限 (entitlements.plist)

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
  <dict>
    <key>com.apple.security.cs.allow-jit</key>
    <true/>
    <key>com.apple.security.automation.apple-events</key>
    <true/>
    <key>com.apple.security.cs.allow-unsigned-executable-memory</key>
    <true/>
    <key>com.apple.security.cs.disable-library-validation</key>
    <true/>
    <key>com.apple.security.device.screen-capture</key>
    <true/>
  </dict>
</plist>

GPU 进程权限 (entitlements.gpu.plist)

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
  <dict>
    <key>com.apple.security.cs.allow-jit</key>
    <true/>
  </dict>
</plist>

插件进程权限 (entitlements.plugin.plist)

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
  <dict>
    <key>com.apple.security.cs.allow-unsigned-executable-memory</key>
    <true/>
    <key>com.apple.security.cs.disable-library-validation</key>
    <true/>
  </dict>
</plist>

关键注意事项

  1. 硬化运行时:必须设置 hardenedRuntime: true 以确保应用符合 macOS 的安全要求
  2. 路径解析:使用 path.resolve 确保权限文件路径正确
  3. 特定权限:根据应用需求添加特定权限,如麦克风访问需要 com.apple.security.device.audio-input
  4. 沙盒模式:如果应用需要沙盒运行,需添加 com.apple.security.app-sandbox 权限

调试技巧

  1. 使用 codesign -dv --verbose=4 /path/to/MyApp.app 检查应用的签名信息
  2. 通过控制台查看权限请求失败的具体原因
  3. 逐步添加权限,测试每项权限的实际效果

通过以上配置,开发者可以解决 Electron Forge 打包 macOS 应用时的签名和权限问题,确保应用能够正确访问所需系统资源。

登录后查看全文
热门项目推荐
相关项目推荐