Skip to content

The agent that grows with you

perf(desktop): reuse Developer ID signatures for loose macOS payload binaries

ethernet92e0717a3aca
diff --git a/.github/workflows/desktop-bundled-release.yml b/.github/workflows/desktop-bundled-release.yml
index 43ab18b3df0..5dcbc22538a 100644
--- a/.github/workflows/desktop-bundled-release.yml
+++ b/.github/workflows/desktop-bundled-release.yml
@@ -1014,11 +1014,25 @@ jobs:
*) echo "::error::actool $version cannot compile .icon packages (need >= 26)"; exit 1 ;;
esac
+ # Developer ID signatures of loose payload binaries, keyed by their unsigned
+ # bytes (apps/desktop/scripts/mac-sign-cache.mjs); every restored file is
+ # re-verified with codesign before use. Commit builds read it with a read-only
+ # cache token and cannot save it.
+ # Saved under a hash of its own contents, so restore takes the newest by prefix.
+ - name: Restore verified macOS payload signatures
+ id: mac-signatures
+ uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0
+ with:
+ path: ${{ github.workspace }}/.cache/mac-payload-signatures
+ key: mac-signatures-v1-${{ matrix.target.label }}
+ restore-keys: mac-signatures-v1-${{ matrix.target.label }}-
+
- name: Build and package
shell: bash
timeout-minutes: 330
env:
HERMES_BUNDLE_ENV_JSON: ${{ inputs.bundle_env }}
+ HERMES_MAC_SIGNATURE_CACHE: ${{ github.workspace }}/.cache/mac-payload-signatures
PYTHONUTF8: '1'
# electron-osx-sign*/electron-notarize* keep the sign+notarize
# phase visible: without them NOTHING logs between "signing
@@ -1063,6 +1077,15 @@ jobs:
echo "signed + notarized: $app"
done
+ # Only signatures from a build Apple notarized are kept for the next run,
+ # and only when this build signed something the restored entry lacked.
+ - name: Save verified macOS payload signatures
+ if: ${{ success() && inputs.build_commit == '' && inputs.channel == '' && (inputs.upload_release == true || inputs.release-phase == 'candidate') && hashFiles('.cache/mac-payload-signatures/**') != '' && steps.mac-signatures.outputs.cache-matched-key != format('mac-signatures-v1-{0}-{1}', matrix.target.label, hashFiles('.cache/mac-payload-signatures/**')) }}
+ uses: actions/cache/save@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0
+ with:
+ path: ${{ github.workspace }}/.cache/mac-payload-signatures
+ key: mac-signatures-v1-${{ matrix.target.label }}-${{ hashFiles('.cache/mac-payload-signatures/**') }}
+
- name: Rename the feed yml per arch
if: inputs.upload_release == true || inputs.release-phase == 'candidate'
# electron-builder writes the channel feed yml (stable-mac.yml /
diff --git a/apps/desktop/electron/channel-build-version.test.ts b/apps/desktop/electron/channel-build-version.test.ts
index 4f511746d6f..6f88dd05657 100644
--- a/apps/desktop/electron/channel-build-version.test.ts
+++ b/apps/desktop/electron/channel-build-version.test.ts
@@ -379,6 +379,7 @@ test('actual MSIX manifest writer consumes the channel quad across rollover inst
'apps/desktop/scripts/before-build.mjs',
'apps/desktop/scripts/mac-icon.cjs',
'apps/desktop/scripts/mac-sign.mjs',
+ 'apps/desktop/scripts/mac-sign-cache.mjs',
'apps/desktop/scripts/payload-digests.mjs',
'apps/desktop/scripts/utils.mjs',
'scripts/msix-shared.mjs',
diff --git a/apps/desktop/scripts/mac-sign-cache.mjs b/apps/desktop/scripts/mac-sign-cache.mjs
new file mode 100644
index 00000000000..90ff9ba5c8f
--- /dev/null
+++ b/apps/desktop/scripts/mac-sign-cache.mjs
@@ -0,0 +1,192 @@
+// Reuse Developer ID signatures for loose Mach-O payload files across release builds.
+//
+// codesign embeds the signature (with a secure timestamp) in the file, so signing
+// is not reproducible: the cache stores the signed bytes, keyed by the unsigned
+// bytes plus everything that shapes the signature. A restored file is verified
+// with codesign before it replaces the unsigned one. Only loose files are
+// cached: a bundle's signature spans its other files, so osx-sign keeps those.
+import { createHash } from 'node:crypto'
+import { execFile } from 'node:child_process'
+import fs from 'node:fs'
+import path from 'node:path'
+import { promisify } from 'node:util'
+
+const exec = promisify(execFile)
+// Thin and fat Mach-O magics, both byte orders (sign-nested-chromium.mjs reads the same set).
+const MACHO_MAGICS = new Set([0xfeedface, 0xcefaedfe, 0xfeedfacf, 0xcffaedfe, 0xcafebabe, 0xbebafeca])
+
+/** @param {string} file */
+function isMachO(file) {
+ const head = Buffer.alloc(4)
+ const fd = fs.openSync(file, 'r')
+ try {
+ return fs.readSync(fd, head, 0, 4, 0) === 4 && MACHO_MAGICS.has(head.readUInt32BE(0))
+ } finally {
+ fs.closeSync(fd)
+ }
+}
+const sha256 = (/** @type {Buffer | string} */ bytes) => createHash('sha256').update(bytes).digest('hex')
+const BUNDLE = /\.(app|framework|bundle|plugin|xpc|appex)$/
+
+/** @typedef {{ key: string, files: string[] }} SignGroup */
+/** @typedef {{ pending: SignGroup[], restored: number }} SignPlan */
+/** @typedef {(file: string, args: string[]) => Promise<void>} Codesign */
+/** @typedef {(files: string[], teamId: string) => Promise<Set<string>>} Verify */
+
+/**
+ * Whether a file lives inside a code bundle below `app` (its seal covers it).
+ * @param {string} app @param {string} file
+ */
+export function insideBundle(app, file) {
+ const parts = path.relative(path.join(app, 'Contents'), path.dirname(file)).split(path.sep)
+ return parts.some(part => BUNDLE.test(part))
+}
+
+/**
+ * Loose Mach-O files under `app/Contents` that the cache may sign: never inside
+ * a nested bundle, never the app's own executable.
+ * @param {string} app @param {(file: string) => boolean} ignore
+ * @returns {string[]}
+ */
+export function looseMachOFiles(app, ignore) {
+ const main = path.join(app, 'Contents', 'MacOS')
+ /** @type {string[]} */
+ const found = []
+ /** @param {string} dir */
+ const walk = dir => {
+ for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
+ const file = path.join(dir, entry.name)
+ if (entry.isSymbolicLink()) continue
+ if (entry.isDirectory()) {
+ if (!BUNDLE.test(entry.name)) walk(file)
+ } else if (entry.isFile() && path.dirname(file) !== main && !ignore(file) && isMachO(file)) {
+ found.push(file)
+ }
+ }
+ }
+ walk(path.join(app, 'Contents'))
+ return found.sort()
+}
+
+/**
+ * Accept only files codesign verifies strictly and that carry this team's
+ * Developer ID, a secure timestamp and the hardened runtime.
+ * @type {Verify}
+ */
+export async function verifySigned(files, teamId) {
+ const valid = new Set()
+ for (const file of files) {
+ try {
+ await exec('codesign', ['--verify', '--strict', file])
+ const { stderr } = await exec('codesign', ['-dvv', file])
+ if (stderr.includes(`TeamIdentifier=${teamId}`) && /^Timestamp=/m.test(stderr) &&
+ /flags=0x[0-9a-f]*\(runtime\)/.test(stderr)) valid.add(file)
+ } catch {
+ // Unsigned, tampered or the wrong team: not a cache entry.
+ }
+ }
+ return valid
+}
+
+/**
+ * The Developer ID team of the signing identity: the "(TEAMID)" suffix of the
+ * certificate's common name, looked up by its SHA-1 hash in the job keychain.
+ * @param {string} identity @param {string | undefined} keychain
+ * @returns {Promise<string | undefined>}
+ */
+export async function identityTeam(identity, keychain) {
+ try {
+ const { stdout } = await exec('security', ['find-identity', '-v', '-p', 'codesigning', ...(keychain ? [keychain] : [])])
+ const line = stdout.split('\n').find(row => row.includes(identity))
+ return line?.match(/Developer ID Application: .*\(([A-Z0-9]{10})\)"/)?.[1]
+ } catch {
+ return undefined
+ }
+}
+
+/** @type {Codesign} */
+async function runCodesign(file, args) {
+ await exec('codesign', [...args, file])
+}
+
+/**
+ * @param {{ root?: string, identity?: string, keychain?: string, teamId?: string, entitlements: string,
+ * codesign?: Codesign, verify?: Verify, concurrency?: number }} options
+ */
+export function createMacSignCache({ root, identity, keychain, teamId, entitlements, codesign = runCodesign,
+ verify = verifySigned, concurrency = 8 }) {
+ if (!root || !teamId || !identity) return null
+ // osx-sign's per-file arguments for a loose binary (sign.js signApplication).
+ const args = ['--sign', identity, '--force', ...(keychain ? ['--keychain', keychain] : []),
+ '--timestamp', '--options', 'runtime', '--entitlements', entitlements]
+ // The keychain is a per-job temp path: it locates the key and never shapes the signature.
+ const policy = sha256(JSON.stringify({ schema: 1, identity, teamId,
+ flags: ['--force', '--timestamp', '--options', 'runtime'],
+ entitlements: sha256(fs.readFileSync(entitlements)) }))
+ const directory = path.join(root, policy)
+ // codesign derives the identifier from the file name, so it is part of the key.
+ const keyOf = (/** @type {string} */ file) => sha256(`${path.basename(file)}\0${sha256(fs.readFileSync(file))}`)
+ const entry = (/** @type {string} */ key) => path.join(directory, key)
+
+ return {
+ /**
+ * Restore every file whose signed bytes are cached and verify; group the
+ * rest so each distinct input is signed once.
+ * @param {string[]} files @returns {Promise<SignPlan>}
+ */
+ async prepare(files) {
+ /** @type {Map<string, SignGroup>} */
+ const groups = new Map()
+ for (const file of files) {
+ const key = keyOf(file)
+ const group = groups.get(key)
+ if (group) group.files.push(file)
+ else groups.set(key, { key, files: [file] })
+ }
+ const candidates = [...groups.values()].filter(group => fs.existsSync(path.join(entry(group.key), 'signed')))
+ const valid = await verify(candidates.map(group => path.join(entry(group.key), 'signed')), teamId)
+ let restored = 0
+ for (const group of candidates) {
+ const signed = path.join(entry(group.key), 'signed')
+ if (!valid.has(signed)) {
+ fs.rmSync(entry(group.key), { recursive: true, force: true })
+ continue
+ }
+ for (const file of group.files) fs.copyFileSync(signed, file)
+ restored += group.files.length
+ groups.delete(group.key)
+ }
+ return { pending: [...groups.values()], restored }
+ },
+
+ /**
+ * Sign each pending group once, verify, store and copy to duplicates.
+ * @param {SignPlan} plan
+ */
+ async sign(plan) {
+ const queue = [...plan.pending]
+ const worker = async () => {
+ for (let group = queue.shift(); group; group = queue.shift()) {
+ await codesign(group.files[0], args)
+ }
+ }
+ await Promise.all(Array.from({ length: Math.min(concurrency, queue.length) }, worker))
+ const firsts = plan.pending.map(group => group.files[0])
+ const valid = await verify(firsts, teamId)
+ for (const group of plan.pending) {
+ const file = group.files[0]
+ if (!valid.has(file)) throw new Error(`Signed payload failed verification: ${file}`)
+ fs.mkdirSync(directory, { recursive: true })
+ const temp = fs.mkdtempSync(path.join(directory, '.tmp-'))
+ try {
+ fs.copyFileSync(file, path.join(temp, 'signed'))
+ // A complete entry appears in one rename, never half-written.
+ if (!fs.existsSync(entry(group.key))) fs.renameSync(temp, entry(group.key))
+ } finally {
+ fs.rmSync(temp, { recursive: true, force: true })
+ }
+ for (const duplicate of group.files.slice(1)) fs.copyFileSync(file, duplicate)
+ }
+ }
+ }
+}
diff --git a/apps/desktop/scripts/mac-sign-cache.test.mjs b/apps/desktop/scripts/mac-sign-cache.test.mjs
new file mode 100644
index 00000000000..ddf5a6e7aba
--- /dev/null
+++ b/apps/desktop/scripts/mac-sign-cache.test.mjs
@@ -0,0 +1,252 @@
+import assert from 'node:assert/strict'
+import fs from 'node:fs'
+import os from 'node:os'
+import path from 'node:path'
+import { execFileSync } from 'node:child_process'
+import { expect, test, vi } from 'vitest'
+
+import { createMacSignCache, insideBundle, looseMachOFiles, verifySigned } from './mac-sign-cache.mjs'
+import { createMacSigner } from './mac-sign.mjs'
+
+const MACHO = Buffer.from([0xcf, 0xfa, 0xed, 0xfe])
+const SIGNED = Buffer.from('\nsigned-by-test')
+
+/** @param {string} marker @returns {Buffer} */
+const machO = marker => Buffer.concat([MACHO, Buffer.from(marker)])
+
+/**
+ * @typedef {object} SigningFixture
+ * @property {string} root
+ * @property {string} app
+ * @property {(relative: string, bytes: Buffer | string) => string} put
+ * @property {import('vitest').Mock<(file: string) => Promise<void>>} codesign
+ * @property {import('vitest').Mock<(files: string[]) => Promise<Set<string>>>} verify
+ * @property {Parameters<typeof createMacSignCache>[0] & { root: string }} opts
+ * @property {() => void} cleanup
+ */
+
+/** @returns {SigningFixture} */
+function fixture() {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'mac-sign-cache-test-'))
+ const entitlements = path.join(root, 'inherit.plist')
+ fs.writeFileSync(entitlements, '<plist/>')
+ const app = path.join(root, 'Hermes.app')
+ /** @param {string} relative @param {Buffer | string} bytes @returns {string} */
+ const put = (relative, bytes) => {
+ const file = path.join(app, 'Contents', relative)
+ fs.mkdirSync(path.dirname(file), { recursive: true })
+ fs.writeFileSync(file, bytes)
+ return file
+ }
+ // Fake codesign appends a signature; fake verify accepts exactly those bytes.
+ const codesign = vi.fn(async (/** @type {string} */ file) => {
+ fs.writeFileSync(file, Buffer.concat([fs.readFileSync(file), SIGNED]))
+ })
+ const verify = vi.fn(async (/** @type {string[]} */ files) =>
+ new Set(files.filter(file => fs.readFileSync(file).subarray(-SIGNED.length).equals(SIGNED))))
+ const opts = { root: path.join(root, 'cache'), identity: 'ABC123', teamId: 'TEAMID1234',
+ entitlements, codesign, verify }
+ return { root, app, put, codesign, verify, opts,
+ cleanup: () => fs.rmSync(root, { recursive: true, force: true }) }
+}
+
+/**
+ * @param {SigningFixture} f
+ * @param {string[]} files
+ * @param {Parameters<typeof createMacSignCache>[0]} [opts]
+ * @returns {Promise<import('./mac-sign-cache.mjs').SignPlan>}
+ */
+async function signAll(f, files, opts = f.opts) {
+ const cache = createMacSignCache(opts)
+ if (!cache) throw new Error('cache disabled')
+ const plan = await cache.prepare(files)
+ await cache.sign(plan)
+ return plan
+}
+
+test('loose payload binaries are found; nested bundles, the main executable and non-Mach-O are not', () => {
+ const f = fixture()
+ try {
+ const loose = f.put('Resources/agent-payload/venv/lib/_core.so', machO('a'))
+ f.put('Resources/agent-payload/README.txt', 'text')
+ f.put('MacOS/Hermes', machO('main'))
+ f.put('Frameworks/Electron Framework.framework/Versions/A/Electron Framework', machO('fw'))
+ f.put('Resources/agent-payload/tools/chromium-1/Chromium.app/Contents/MacOS/Chromium', machO('c'))
+ expect(looseMachOFiles(f.app, () => false)).toEqual([loose])
+ expect(looseMachOFiles(f.app, file => file === loose)).toEqual([])
+ expect(insideBundle(f.app, path.join(f.app, 'Contents/Frameworks/X.framework/Versions/A/X'))).toBe(true)
+ expect(insideBundle(f.app, loose)).toBe(false)
+ } finally {
+ f.cleanup()
+ }
+})
+
+test('an identical input restores the stored signed bytes without signing again', async () => {
+ const f = fixture()
+ try {
+ const first = f.put('Resources/agent-payload/venv/lib/_core.so', machO('a'))
+ await signAll(f, [first])
+ const signed = fs.readFileSync(first)
+ expect(f.codesign).toHaveBeenCalledTimes(1)
+
+ const again = f.put('Resources/agent-payload/venv/lib/_core.so', machO('a'))
+ const plan = await signAll(f, [again])
+ expect(plan.restored).toBe(1)
+ expect(f.codesign).toHaveBeenCalledTimes(1)
+ expect(fs.readFileSync(again).equals(signed)).toBe(true)
+ } finally {
+ f.cleanup()
+ }
+})
+
+test('duplicate inputs with the same name are signed once and all receive the signature', async () => {
+ const f = fixture()
+ try {
+ const files = ['venv/lib/_core.so', 'uv-cache/wheels/_core.so', 'uv-cache/archive/_core.so']
+ .map(relative => f.put(`Resources/agent-payload/${relative}`, machO('same')))
+ const plan = await signAll(f, files)
+ expect(plan.pending).toHaveLength(1)
+ expect(f.codesign).toHaveBeenCalledTimes(1)
+ for (const file of files) expect(fs.readFileSync(file).subarray(-SIGNED.length).equals(SIGNED)).toBe(true)
+ } finally {
+ f.cleanup()
+ }
+})
+
+test('the file name, team, identity and entitlements are part of the key', async () => {
+ const f = fixture()
+ try {
+ await signAll(f, [f.put('Resources/a/_core.so', machO('x'))])
+ // Same bytes, different name: codesign derives the identifier from the name.
+ await signAll(f, [f.put('Resources/a/_other.so', machO('x'))])
+ expect(f.codesign).toHaveBeenCalledTimes(2)
+ await signAll(f, [f.put('Resources/a/_core.so', machO('x'))], { ...f.opts, teamId: 'OTHERTEAM1' })
+ await signAll(f, [f.put('Resources/a/_core.so', machO('x'))], { ...f.opts, identity: 'DEF456' })
+ fs.writeFileSync(f.opts.entitlements, '<plist>changed</plist>')
+ await signAll(f, [f.put('Resources/a/_core.so', machO('x'))])
+ expect(f.codesign).toHaveBeenCalledTimes(5)
+ } finally {
+ f.cleanup()
+ }
+})
+
+test('a cached entry the verifier rejects is evicted and the file is signed afresh', async () => {
+ const f = fixture()
+ try {
+ const file = f.put('Resources/a/_core.so', machO('x'))
+ await signAll(f, [file])
+ const [policy] = fs.readdirSync(f.opts.root)
+ const [key] = fs.readdirSync(path.join(f.opts.root, policy))
+ fs.writeFileSync(path.join(f.opts.root, policy, key, 'signed'), machO('tampered'))
+
+ const again = f.put('Resources/a/_core.so', machO('x'))
+ const plan = await signAll(f, [again])
+ expect(plan.restored).toBe(0)
+ expect(f.codesign).toHaveBeenCalledTimes(2)
+ expect(fs.readFileSync(again).subarray(-SIGNED.length).equals(SIGNED)).toBe(true)
+ } finally {
+ f.cleanup()
+ }
+})
+
+test('a signature that fails verification is never stored', async () => {
+ const f = fixture()
+ try {
+ const file = f.put('Resources/a/_core.so', machO('x'))
+ const cache = createMacSignCache({ ...f.opts, verify: async () => new Set() })
+ if (!cache) throw new Error('cache disabled')
+ await expect(cache.sign(await cache.prepare([file]))).rejects.toThrow('failed verification')
+ expect(fs.existsSync(f.opts.root) ? fs.readdirSync(f.opts.root).flatMap(p =>
+ fs.readdirSync(path.join(f.opts.root, p)).filter(e => !e.startsWith('.tmp-'))) : []).toEqual([])
+ } finally {
+ f.cleanup()
+ }
+})
+
+test('without a cache root, team or identity the cache is off', () => {
+ const f = fixture()
+ try {
+ expect(createMacSignCache({ ...f.opts, root: undefined })).toBeNull()
+ expect(createMacSignCache({ ...f.opts, teamId: undefined })).toBeNull()
+ expect(createMacSignCache({ ...f.opts, identity: undefined })).toBeNull()
+ } finally {
+ f.cleanup()
+ }
+})
+
+test('the signer hands cache-signed binaries to osx-sign as ignored and still seals everything else', async () => {
+ const f = fixture()
+ try {
+ const loose = f.put('Resources/agent-payload/venv/lib/_core.so', machO('a'))
+ const framework = f.put('Frameworks/X.framework/Versions/A/X', machO('fw'))
+ const policyIgnored = f.put('Resources/policy.so', machO('policy'))
+ const inheritedIgnored = f.put('Resources/inherited.so', machO('inherited'))
+ const keychain = path.join(f.root, 'release.keychain-db')
+ const sign = vi.fn(async (/** @type {import('@electron/osx-sign').SignOptions} */ opts) => {
+ expect(fs.readFileSync(loose)).toEqual(Buffer.concat([machO('a'), SIGNED]))
+ assert(opts.ignore instanceof Function)
+ expect(opts.ignore(loose)).toBe(true)
+ expect(opts.ignore(policyIgnored)).toBe(true)
+ expect(opts.ignore(inheritedIgnored)).toBe(true)
+ expect(opts.ignore(framework)).toBe(false)
+ expect(opts.ignore(f.app)).toBe(false)
+ expect(opts.identity).toBe(f.opts.identity)
+ expect(opts.keychain).toBe(keychain)
+ expect(opts.batchCodesignCalls).toBe(false)
+ })
+ const signer = createMacSigner(
+ { entitlements: 'app.plist', entitlementsInherit: f.opts.entitlements, hardenedRuntime: true,
+ ignore: file => file === policyIgnored },
+ { env: { HERMES_MAC_SIGNATURE_CACHE: f.opts.root }, sign,
+ team: async () => 'TEAMID1234',
+ makeCache: options => createMacSignCache({ ...options, codesign: f.codesign, verify: f.verify }) })
+ const packager = { helper: { getOptionsForFile: async () => () => ({}) } }
+ /** @type {import('@electron/osx-sign').SignOptions} */
+ const opts = { app: f.app, platform: 'darwin', identity: f.opts.identity, keychain,
+ ignore: file => file === inheritedIgnored }
+ await signer(opts, packager)
+ expect(f.codesign).toHaveBeenCalledExactlyOnceWith(loose, [
+ '--sign', f.opts.identity, '--force', '--keychain', keychain,
+ '--timestamp', '--options', 'runtime', '--entitlements', f.opts.entitlements
+ ])
+ f.put('Resources/agent-payload/venv/lib/_core.so', machO('a'))
+ await signer(opts, packager)
+ expect(f.codesign).toHaveBeenCalledTimes(1)
+ expect(sign).toHaveBeenCalledTimes(2)
+ } finally {
+ f.cleanup()
+ }
+})
+
+test('the signer does not seal an app when cache signing fails verification', async () => {
+ const f = fixture()
+ try {
+ f.put('Resources/agent-payload/venv/lib/_core.so', machO('a'))
+ const sign = vi.fn(async (/** @type {import('@electron/osx-sign').SignOptions} */ _opts) => {})
+ const signer = createMacSigner(
+ { entitlementsInherit: f.opts.entitlements, hardenedRuntime: true, ignore: () => false },
+ { env: { HERMES_MAC_SIGNATURE_CACHE: f.opts.root }, sign,
+ team: async () => 'TEAMID1234',
+ makeCache: options => createMacSignCache({ ...options, codesign: f.codesign, verify: async () => new Set() }) })
+ const packager = { helper: { getOptionsForFile: async () => () => ({}) } }
+ await expect(signer({ app: f.app, platform: 'darwin', identity: f.opts.identity }, packager))
+ .rejects.toThrow('failed verification')
+ expect(f.codesign).toHaveBeenCalledTimes(1)
+ expect(sign).not.toHaveBeenCalled()
+ } finally {
+ f.cleanup()
+ }
+})
+
+test.runIf(process.platform === 'darwin')('native verification accepts only a Developer ID, timestamped, hardened signature', async () => {
+ const f = fixture()
+ try {
+ // An ad-hoc signature verifies, but has no team, timestamp or Developer ID.
+ const file = path.join(f.root, 'true')
+ fs.copyFileSync('/usr/bin/true', file)
+ execFileSync('codesign', ['--force', '--sign', '-', '--options', 'runtime', file])
+ expect(await verifySigned([file], 'TEAMID1234')).toEqual(new Set())
+ } finally {
+ f.cleanup()
+ }
+})
diff --git a/apps/desktop/scripts/mac-sign.mjs b/apps/desktop/scripts/mac-sign.mjs
index 9ec198196df..a92cd0aa57e 100644
--- a/apps/desktop/scripts/mac-sign.mjs
+++ b/apps/desktop/scripts/mac-sign.mjs
@@ -1,20 +1,45 @@
import path from 'node:path'
+import { createMacSignCache, identityTeam, looseMachOFiles } from './mac-sign-cache.mjs'
import { rehashPayloadDigests } from './payload-digests.mjs'
/**
* @param {Pick<import('app-builder-lib').ElectronSignOptions, 'entitlements' | 'entitlementsInherit' | 'hardenedRuntime'> & { ignore: (file: string) => boolean }} policy
- * @returns {(opts: import('@electron/osx-sign').SignOptions, packager: import('app-builder-lib').MacPackager) => Promise<void>}
+ * @param {{ env?: NodeJS.ProcessEnv, makeCache?: typeof createMacSignCache, team?: typeof identityTeam, sign?: typeof import('@electron/osx-sign').sign }} [deps]
+ * @returns {(opts: import('@electron/osx-sign').SignOptions, packager: { helper: Pick<import('app-builder-lib').MacPackager['helper'], 'getOptionsForFile'> }) => Promise<void>}
*/
-export function createMacSigner(policy) {
+export function createMacSigner(policy, { env = process.env, makeCache = createMacSignCache, team = identityTeam, sign: signApp } = {}) {
return async (opts, packager) => {
const target = opts.platform === 'mas' ? (opts.type === 'development' ? 'mas-dev' : 'mas') : 'mac'
const optionsForFile = await packager.helper.getOptionsForFile(opts.app, target, policy)
const inheritedIgnore = opts.ignore
- const { sign } = await import('@electron/osx-sign')
+ /** @param {string} file */
+ const ignored = file => (typeof inheritedIgnore === 'function' && inheritedIgnore(file)) || policy.ignore(file)
+ // Release builds (HERMES_MAC_SIGNATURE_CACHE) sign loose payload binaries through
+ // the signature cache with the arguments osx-sign would use (inherited
+ // entitlements, hardened runtime, secure timestamp); osx-sign then skips them
+ // and still seals every bundle and the app.
+ const identity = opts.identity
+ const enabled = target === 'mac' && env.HERMES_MAC_SIGNATURE_CACHE && identity &&
+ policy.entitlementsInherit && policy.hardenedRuntime
+ const cache = enabled && policy.entitlementsInherit ? makeCache({
+ root: env.HERMES_MAC_SIGNATURE_CACHE, teamId: await team(identity, opts.keychain), identity,
+ keychain: opts.keychain, entitlements: policy.entitlementsInherit
+ }) : null
+ /** @type {Set<string>} */
+ const presigned = new Set()
+ if (cache) {
+ const files = looseMachOFiles(opts.app, ignored)
+ const plan = await cache.prepare(files)
+ await cache.sign(plan)
+ for (const file of files) presigned.add(file)
+ console.log(`mac signature cache: ${files.length} loose binaries, ${plan.restored} restored, ` +
+ `${plan.pending.length} signed`)
+ }
+ const sign = signApp ?? (await import('@electron/osx-sign')).sign
await sign({
...opts,
- ignore: file => (typeof inheritedIgnore === 'function' && inheritedIgnore(file)) || policy.ignore(file),
+ ignore: file => presigned.has(file) || ignored(file),
// Batching defers child signatures until after all option callbacks.
batchCodesignCalls: false,
optionsForFile: file => {