Merge pull request #159835 from NousResearch/fix/mac-dmg-sign-notarize
Some checks failed
Deploy Site / deploy-vercel (push) Has been cancelled
Deploy Site / deploy-docs (push) Has been cancelled
auto-fix lint issues & formatting / Generate eslint --fix patch (push) Has been cancelled
auto-fix lint issues & formatting / Apply patch (push) Has been cancelled
Skills Index Freshness Check / check-freshness (push) Has been cancelled
Skills Index Freshness Check / check-catalog-cors (push) Has been cancelled
Docs Search Monitor / probe (push) Has been cancelled

fix(desktop): sign, notarize, staple, and verify outer macOS DMG
This commit is contained in:
Bear Huddleston
2026-11-25 12:55:52 -06:00
committed by GitHub
14 changed files with 1294 additions and 64 deletions

View File

@@ -123,7 +123,10 @@ module.exports = {
// rewritten file (#105629). afterPack keeps the signing/payload work.
afterExtract: 'scripts/after-extract.mjs',
afterPack: 'scripts/after-pack.mjs',
...(process.platform === 'darwin' ? { afterSign: 'scripts/notarize.mjs' } : {}),
// dmg-builder's dmg.sign omits --timestamp and pre-dates stapling; artifactBuildCompleted signs, notarizes, staples, and refreshes blockmap/feed bytes before artifactCreated fires.
...(process.platform === 'darwin'
? { afterSign: 'scripts/notarize.mjs', artifactBuildCompleted: 'scripts/notarize-dmg.mjs' }
: {}),
extraResources: [
{
from: 'build/install-stamp.json',

View File

@@ -93,6 +93,8 @@ export interface InstallStamp {
channelBuild?: Readonly<ChannelBuildRequest>
/** Cross-application receiver shipped in this artifact, absent on older builds. */
receiverProtocol?: 1
/** Outer macOS DMG signed and notarized by this build's packaging hooks. */
signedDmg?: true
/** Pinned release tag; null for channel builds, one-offs and bootstrap. */
tag: string | null
}

View File

@@ -3,6 +3,14 @@ import path from 'node:path'
import { createMacSignCache, identityTeam, looseMachOFiles } from './mac-sign-cache.mjs'
import { rehashPayloadDigests } from './payload-digests.mjs'
/** @type {WeakMap<object, { identity: string | null, keychain: string | null }>} */
const appSigningResults = new WeakMap()
/** @param {object | null | undefined} packager */
export function getAppSigningResult(packager) {
return packager && typeof packager === 'object' ? (appSigningResults.get(packager) ?? null) : null
}
/**
* @param {Pick<import('app-builder-lib').ElectronSignOptions, 'entitlements' | 'entitlementsInherit' | 'hardenedRuntime'> & { ignore: (file: string) => boolean }} policy
* @param {{ env?: NodeJS.ProcessEnv, makeCache?: typeof createMacSignCache, team?: typeof identityTeam, sign?: typeof import('@electron/osx-sign').sign }} [deps]
@@ -49,5 +57,8 @@ export function createMacSigner(policy, { env = process.env, makeCache = createM
return optionsForFile(file)
}
})
if (target === 'mac' && packager && typeof packager === 'object') {
appSigningResults.set(packager, { identity: opts.identity ?? null, keychain: opts.keychain ?? null })
}
}
}

View File

@@ -0,0 +1,119 @@
import fs from 'node:fs'
import { setTimeout } from 'node:timers/promises'
import { getAppSigningResult } from './mac-sign.mjs'
import { remainingNotaryBudgetMs, resolveNotaryAuth, runCommand, submitAndStaple, validateStapled } from './notarize.mjs'
export async function resolveDmgSigningIdentity(packager, { env = process.env } = {}) {
// Only the certificate electron-builder signed the app with may sign its DMG; never pick another one.
const recorded = getAppSigningResult(packager)
if (recorded) {
return {
identity: recorded.identity === '-' ? null : recorded.identity,
keychain: recorded.keychain
}
}
// The app is unsigned: the signing settings only decide whether that was intended.
const signConfig = packager?.platformOptions?.sign
if (signConfig === null || (typeof signConfig === 'object' && signConfig?.identity === null)) {
return { identity: null, keychain: null }
}
const rawQualifier = (typeof signConfig === 'object' && signConfig !== null ? signConfig.identity : undefined) ?? env.CSC_NAME
const qualifier = typeof rawQualifier === 'string' && rawQualifier.trim() ? rawQualifier.trim() : null
if (qualifier === '-' || (!qualifier && env.CSC_IDENTITY_AUTO_DISCOVERY === 'false')) {
return { identity: null, keychain: null }
}
const info = await packager?.codeSigningInfo?.value
const keychain = info?.keychainFile || env.CSC_KEYCHAIN || null
if (keychain || qualifier) {
throw new Error(
`notarize-dmg: signing is configured (${keychain || qualifier}), but electron-builder did not sign the app`
)
}
return { identity: null, keychain: null }
}
async function refreshDmgBlockmap(dmgPath, event, buildBlockMap, log) {
const blockMapFile = `${dmgPath}.blockmap`
if (!fs.existsSync(blockMapFile) && !event.isWriteUpdateInfo && event.updateInfo == null) {
return
}
const rebuild = buildBlockMap ?? (await import('app-builder-lib/internal')).buildBlockMap
const updated = await rebuild(dmgPath, 'gzip', blockMapFile)
if (event.updateInfo && typeof event.updateInfo === 'object') {
Object.assign(event.updateInfo, updated)
} else {
event.updateInfo = updated
}
log(`[notarize-dmg] refreshed blockmap and update metadata for ${dmgPath} (${updated.size} bytes)`)
}
export default async function notarizeDmg(
event,
{
run = runCommand,
env = process.env,
sleep = setTimeout,
log = console.log,
now = () => performance.now(),
buildBlockMap
} = {}
) {
if (!event || event.target?.name !== 'dmg' || typeof event.file !== 'string' || !event.file.endsWith('.dmg')) {
return
}
if (event.packager?.platform?.nodeName && event.packager.platform.nodeName !== 'darwin') {
return
}
const dmgPath = event.file
if (!fs.existsSync(dmgPath)) {
throw new Error(`Cannot sign or notarize missing DMG artifact: ${dmgPath}`)
}
const notaryAuth = resolveNotaryAuth(env)
try {
const { identity, keychain } = await resolveDmgSigningIdentity(event.packager, { env })
if (!identity) {
if (notaryAuth) {
throw new Error(`Cannot notarize DMG without a Developer ID Application signing identity: ${dmgPath}`)
}
log('[notarize-dmg] Skipping DMG signing and notarization: no Developer ID Application identity configured.')
return
}
log(`[notarize-dmg] signing ${dmgPath}`)
const signArgs = ['--force', '--sign', identity, '--timestamp', '--verbose']
if (keychain) signArgs.push('--keychain', keychain)
signArgs.push(dmgPath)
await run('codesign', signArgs)
await run('codesign', ['--verify', '--verbose=2', dmgPath])
if (notaryAuth) {
const waitBudgetMs = remainingNotaryBudgetMs({ now })
const { deadline } = await submitAndStaple(dmgPath, dmgPath, notaryAuth.auth, {
run,
sleep,
log,
now,
label: 'notarize-dmg',
waitBudgetMs
})
await run('codesign', ['--verify', '--verbose=2', dmgPath])
await validateStapled(dmgPath, { run, sleep, log, now, deadline, label: 'notarize-dmg' })
await run('spctl', ['-a', '-vv', '-t', 'open', '--context', 'context:primary-signature', dmgPath])
log(`[notarize-dmg] verified signed, stapled, and Gatekeeper-accepted DMG: ${dmgPath}`)
} else {
log(
'[notarize-dmg] Skipping DMG notarization: APPLE_API_KEY, APPLE_API_KEY_ID, and APPLE_API_ISSUER are not fully configured.'
)
}
await refreshDmgBlockmap(dmgPath, event, buildBlockMap, log)
} finally {
notaryAuth?.cleanup()
}
}

View File

@@ -0,0 +1,561 @@
import { createHash } from 'node:crypto'
import fs from 'node:fs'
import { createRequire } from 'node:module'
import os from 'node:os'
import path from 'node:path'
import zlib from 'node:zlib'
import { Arch, MacPackager, Packager, Platform, PublishManager } from 'app-builder-lib'
import { buildBlockMap, createBlockmap, validateConfiguration } from 'app-builder-lib/internal'
import jsYaml from 'js-yaml'
import { afterEach, expect, test, vi } from 'vitest'
import { createMacSigner } from './mac-sign.mjs'
import notarize, { COMBINED_NOTARY_BUDGET_MS, DMG_VERIFY_RESERVE_MS } from './notarize.mjs'
import notarizeDmg, { resolveDmgSigningIdentity } from './notarize-dmg.mjs'
const require = createRequire(import.meta.url)
const desktopDir = path.resolve(import.meta.dirname, '..')
const builderConfig = require(path.join(desktopDir, 'electron-builder.config.cjs'))
const IDENTITY_HASH = '0123456789ABCDEF0123456789ABCDEF01234567'
const SECOND_IDENTITY_HASH = 'FEDCBA9876543210FEDCBA9876543210FEDCBA98'
const IDENTITY_LIST = ` 1) ${IDENTITY_HASH} "Developer ID Application: Nous Research (TEAM123456)"\n 1 valid identities found\n`
const TWO_IDENTITY_LIST =
` 1) ${IDENTITY_HASH} "Developer ID Application: Other Org (OTHER12345)"\n` +
` 2) ${SECOND_IDENTITY_HASH} "Developer ID Application: Nous Research (TEAM123456)"\n` +
' 2 valid identities found\n'
const SUBMISSION_ID = '00000000-0000-4000-8000-000000000042'
const NOTARY_TIMEOUT = `Error: HTTPError(statusCode: nil, error: Error Domain=NSURLErrorDomain Code=-1001 "The request timed out." UserInfo={NSErrorFailingURLStringKey=https://appstoreconnect.apple.com/notary/v2/submissions/${SUBMISSION_ID}?})`
const CONNECTION_LOST = 'error is Error Domain=NSURLErrorDomain Code=-1005 "The network connection was lost."\nThe staple and validate action failed! Error 68.'
const MISSING_TICKET = Object.assign(
new Error('CloudKit query for Hermes.dmg failed due to "Record not found".\nThe staple and validate action failed! Error 65.'),
{ code: 65 }
)
/** @type {string[]} */
const roots = []
afterEach(() => {
for (const root of roots.splice(0)) fs.rmSync(root, { recursive: true, force: true })
})
function sha512Base64(bytes) {
return createHash('sha512').update(bytes).digest('base64')
}
async function createBuilderFixture({
keychainFile,
platformOptions = { sign: () => {} },
preStapleBytes = Buffer.from('udif-dmg-unsigned-payload-'.repeat(600))
} = {}) {
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'hermes-dmg-notarize-'))
roots.push(root)
const effectiveKeychain = keychainFile === undefined ? path.join(root, 'builder.keychain') : keychainFile
const outDir = path.join(root, 'release')
fs.mkdirSync(outDir, { recursive: true })
fs.writeFileSync(
path.join(root, 'package.json'),
JSON.stringify({ name: 'hermes-fixture', version: '1.2.3', description: 'fixture', author: 'Test' })
)
const info = new Packager({
projectDir: root,
config: {
appId: 'ai.hermes.fixture',
productName: 'Hermes Fixture',
directories: { output: outDir },
mac: {
publish: [{ provider: 'generic', url: 'https://updates.example/releases/darwin/stable/', channel: 'stable' }]
}
}
})
await info.validateConfig()
info._appInfo = new (await import('app-builder-lib')).AppInfo(info, null)
const publishManager = new PublishManager(info, { publish: 'never' })
const packager = new MacPackager(info)
Object.assign(packager.platformSpecificBuildOptions, platformOptions)
packager.codeSigningInfo = { value: Promise.resolve({ keychainFile: effectiveKeychain }) }
const dmgPath = path.join(outDir, 'HermesBundled-1.2.3-mac-arm64.dmg')
const zipPath = path.join(outDir, 'HermesBundled-1.2.3-mac-arm64.zip')
fs.writeFileSync(dmgPath, preStapleBytes)
fs.writeFileSync(zipPath, Buffer.from('signed-app-zip-bytes'))
const dmgTarget = { name: 'dmg', outDir, options: {} }
const zipTarget = { name: 'zip', outDir, options: {} }
const keyFile = path.join(root, 'api-key.p8')
fs.writeFileSync(keyFile, 'test-key-file')
return {
root,
outDir,
keychainFile: effectiveKeychain,
info,
publishManager,
packager,
dmgPath,
zipPath,
dmgTarget,
zipTarget,
preStapleBytes,
signedEnv: {
APPLE_API_KEY: keyFile,
APPLE_API_KEY_ID: 'KEY123',
APPLE_API_ISSUER: 'ISSUER456'
}
}
}
/** Sign the fixture's app through createMacSigner, as electron-builder does before afterSign and the DMG hook. */
async function signAppWith(f, identity = IDENTITY_HASH) {
const appPath = path.join(f.outDir, 'Hermes Fixture.app')
fs.mkdirSync(path.join(appPath, 'Contents', 'Resources', 'agent-payload'), { recursive: true })
const signer = createMacSigner(
{ hardenedRuntime: true, entitlements: 'ent.plist', entitlementsInherit: 'ent.plist', ignore: () => false },
{ env: {}, sign: vi.fn(async () => {}) }
)
await signer(
{ app: appPath, platform: 'darwin', type: 'distribution', identity, keychain: f.keychainFile },
Object.assign(f.packager, { helper: { getOptionsForFile: async () => () => ({}) } })
)
}
test('signed and notarized DMG signs with timestamp, retries notary/stapler/validate, verifies Gatekeeper, and updates blockmap and stable-mac.yml to post-staple bytes', async () => {
const f = await createBuilderFixture()
await signAppWith(f)
const signedTrailer = Buffer.from('\n--CODESIGN-CMS-TIMESTAMP-SIGNATURE--')
const ticketTrailer = Buffer.from('\n--APPLE-NOTARIZATION-STAPLED-TICKET--')
const calls = []
let notaryCalls = 0
let stapleCalls = 0
let validateCalls = 0
let elapsed = 0
const run = vi.fn(async (command, args) => {
calls.push([command, ...args])
if (command === 'security') return { stdout: IDENTITY_LIST, stderr: '' }
if (command === 'codesign' && args.includes('--sign')) {
fs.appendFileSync(args.at(-1), signedTrailer)
return { stdout: '', stderr: '' }
}
if (command === 'codesign' && args.includes('--verify')) {
return { stdout: '', stderr: '' }
}
if (command === 'xcrun' && args[0] === 'notarytool') {
notaryCalls += 1
if (notaryCalls === 1) {
elapsed += 60_000
throw Object.assign(new Error(NOTARY_TIMEOUT), { code: 1, stderr: NOTARY_TIMEOUT })
}
return { stdout: JSON.stringify({ id: SUBMISSION_ID, status: 'Accepted' }), stderr: '' }
}
if (command === 'xcrun' && args[0] === 'stapler' && args[1] === 'staple') {
stapleCalls += 1
if (stapleCalls === 1) throw MISSING_TICKET
if (stapleCalls === 2) throw Object.assign(new Error(CONNECTION_LOST), { code: 68 })
fs.appendFileSync(args.at(-1), ticketTrailer)
return { stdout: 'The staple and validate action worked!', stderr: '' }
}
if (command === 'xcrun' && args[0] === 'stapler' && args[1] === 'validate') {
validateCalls += 1
if (validateCalls === 1) throw Object.assign(new Error(CONNECTION_LOST), { code: 68 })
return { stdout: 'The validate action worked!', stderr: '' }
}
if (command === 'spctl') {
return { stdout: '', stderr: `${f.dmgPath}: accepted\nsource=Notarized Developer ID\n` }
}
throw new Error(`Unexpected command: ${command} ${args.join(' ')}`)
})
const sleep = vi.fn(async ms => {
elapsed += ms
})
const log = vi.fn()
f.info.eventEmitter.on(
'artifactBuildCompleted',
event => notarizeDmg(event, { run, env: f.signedEnv, sleep, log, now: () => elapsed }),
'user'
)
const preStapleUpdateInfo = await createBlockmap(f.dmgPath, f.dmgTarget, f.packager, path.basename(f.dmgPath))
expect(preStapleUpdateInfo.size).toBe(f.preStapleBytes.length)
await f.packager.emitArtifactBuildCompleted({
file: f.dmgPath,
safeArtifactName: path.basename(f.dmgPath),
target: f.dmgTarget,
arch: Arch.arm64,
packager: f.packager,
isWriteUpdateInfo: true,
updateInfo: preStapleUpdateInfo
})
const zipUpdateInfo = await createBlockmap(f.zipPath, f.zipTarget, f.packager, path.basename(f.zipPath))
await f.packager.emitArtifactBuildCompleted({
file: f.zipPath,
safeArtifactName: path.basename(f.zipPath),
target: f.zipTarget,
arch: Arch.arm64,
packager: f.packager,
isWriteUpdateInfo: true,
updateInfo: zipUpdateInfo
})
await f.publishManager.awaitTasks()
const finalBytes = fs.readFileSync(f.dmgPath)
expect(finalBytes.equals(Buffer.concat([f.preStapleBytes, signedTrailer, ticketTrailer]))).toBe(true)
expect(calls.filter(c => c[0] === 'ditto')).toHaveLength(0)
expect(calls).toContainEqual([
'codesign', '--force', '--sign', IDENTITY_HASH, '--timestamp', '--verbose', '--keychain', f.keychainFile, f.dmgPath
])
expect(calls.filter(c => c[0] === 'codesign' && c[1] === '--verify' && c[2] === '--verbose=2' && c[3] === f.dmgPath)).toHaveLength(2)
expect(calls.filter(c => c[0] === 'xcrun' && c[1] === 'notarytool' && c[2] === 'submit')).toHaveLength(1)
expect(calls.filter(c => c[0] === 'xcrun' && c[1] === 'notarytool' && c[2] === 'wait' && c[3] === SUBMISSION_ID)).toHaveLength(1)
expect(stapleCalls).toBe(3)
expect(validateCalls).toBe(2)
expect(calls).toContainEqual(['spctl', '-a', '-vv', '-t', 'open', '--context', 'context:primary-signature', f.dmgPath])
const blockmap = JSON.parse(zlib.gunzipSync(fs.readFileSync(`${f.dmgPath}.blockmap`)).toString('utf8'))
const coveredBytes = blockmap.files[0].sizes.reduce((sum, n) => sum + n, 0)
expect(coveredBytes).toBe(finalBytes.length)
expect(coveredBytes).not.toBe(f.preStapleBytes.length)
const freshBlockmapPath = path.join(f.root, 'fresh.blockmap')
const fresh = await buildBlockMap(f.dmgPath, 'gzip', freshBlockmapPath)
expect(fs.readFileSync(`${f.dmgPath}.blockmap`).equals(fs.readFileSync(freshBlockmapPath))).toBe(true)
const feed = jsYaml.load(fs.readFileSync(path.join(f.outDir, 'stable-mac.yml'), 'utf8'))
const dmgEntry = feed.files.find(entry => entry.url === path.basename(f.dmgPath))
expect(dmgEntry).toBeDefined()
expect(dmgEntry.size).toBe(finalBytes.length)
expect(dmgEntry.sha512).toBe(sha512Base64(finalBytes))
expect(dmgEntry.sha512).toBe(fresh.sha512)
expect(dmgEntry.sha512).not.toBe(sha512Base64(f.preStapleBytes))
expect(feed.files[0].url).toBe(path.basename(f.zipPath))
})
test('signed local build without Apple notary credentials signs DMG and refreshes blockmap/updateInfo without notarizing', async () => {
const f = await createBuilderFixture()
await signAppWith(f)
const signedTrailer = Buffer.from('\n--LOCAL-SIGN-ONLY--')
const calls = []
const run = vi.fn(async (command, args) => {
calls.push([command, ...args])
if (command === 'security') return { stdout: IDENTITY_LIST, stderr: '' }
if (command === 'codesign' && args.includes('--sign')) {
fs.appendFileSync(args.at(-1), signedTrailer)
}
return { stdout: '', stderr: '' }
})
const updateInfo = await createBlockmap(f.dmgPath, f.dmgTarget, f.packager, path.basename(f.dmgPath))
await notarizeDmg(
{
file: f.dmgPath,
target: f.dmgTarget,
packager: f.packager,
isWriteUpdateInfo: true,
updateInfo
},
{ run, env: {}, sleep: vi.fn(), log: vi.fn() }
)
const signedBytes = fs.readFileSync(f.dmgPath)
expect(signedBytes.equals(Buffer.concat([f.preStapleBytes, signedTrailer]))).toBe(true)
expect(calls.some(c => c[0] === 'xcrun')).toBe(false)
expect(calls.some(c => c[0] === 'spctl')).toBe(false)
expect(updateInfo.size).toBe(signedBytes.length)
expect(updateInfo.sha512).toBe(sha512Base64(signedBytes))
const blockmap = JSON.parse(zlib.gunzipSync(fs.readFileSync(`${f.dmgPath}.blockmap`)).toString('utf8'))
expect(blockmap.files[0].sizes.reduce((sum, n) => sum + n, 0)).toBe(signedBytes.length)
})
test('unsigned local builds skip outer DMG signing even when valid Developer ID certificates exist in the keychain', async () => {
const cases = [
{ name: 'CSC_IDENTITY_AUTO_DISCOVERY=false', env: { CSC_IDENTITY_AUTO_DISCOVERY: 'false' }, platformOptions: {}, keychainFile: null, stdout: TWO_IDENTITY_LIST },
{ name: 'mac.sign=null', env: {}, platformOptions: { sign: null }, keychainFile: null, stdout: TWO_IDENTITY_LIST },
{ name: 'mac.sign.identity=null', env: {}, platformOptions: { sign: { identity: null } }, keychainFile: null, stdout: TWO_IDENTITY_LIST },
{ name: 'ad-hoc CSC_NAME=-', env: { CSC_NAME: '-' }, platformOptions: {}, keychainFile: null, stdout: TWO_IDENTITY_LIST },
{ name: 'no Developer ID in default keychain', env: {}, platformOptions: {}, keychainFile: null, stdout: ' 0 valid identities found\n' }
]
for (const scenario of cases) {
const f = await createBuilderFixture({ keychainFile: scenario.keychainFile, platformOptions: scenario.platformOptions })
const run = vi.fn(async command => {
if (command === 'security') return { stdout: scenario.stdout, stderr: '' }
throw new Error(`Unexpected command for ${scenario.name}: ${command}`)
})
await notarizeDmg(
{ file: f.dmgPath, target: f.dmgTarget, packager: f.packager, isWriteUpdateInfo: true, updateInfo: { size: f.preStapleBytes.length, sha512: sha512Base64(f.preStapleBytes) } },
{ run, env: scenario.env, sleep: vi.fn(), log: vi.fn() }
)
expect(fs.readFileSync(f.dmgPath).equals(f.preStapleBytes), scenario.name).toBe(true)
if (scenario.stdout === TWO_IDENTITY_LIST) {
expect(run, scenario.name).not.toHaveBeenCalled()
} else {
expect(run.mock.calls.every(([cmd]) => cmd === 'security'), scenario.name).toBe(true)
}
}
})
test('DMG reuses the exact identity and keychain recorded by createMacSigner when multiple certificates exist', async () => {
const f = await createBuilderFixture()
const appPath = path.join(f.outDir, 'Hermes Fixture.app')
fs.mkdirSync(path.join(appPath, 'Contents', 'Resources', 'agent-payload'), { recursive: true })
const signer = createMacSigner(
{ hardenedRuntime: true, entitlements: 'ent.plist', entitlementsInherit: 'ent.plist', ignore: () => false },
{ env: {}, sign: vi.fn(async () => {}) }
)
await signer(
{ app: appPath, platform: 'darwin', type: 'distribution', identity: SECOND_IDENTITY_HASH, keychain: f.keychainFile },
Object.assign(f.packager, { helper: { getOptionsForFile: async () => () => ({}) } })
)
const calls = []
const run = vi.fn(async (command, args) => {
calls.push([command, ...args])
if (command === 'security') throw new Error('DMG hook must not re-query security find-identity after app signing')
if (command === 'xcrun' && args[0] === 'notarytool') {
return { stdout: JSON.stringify({ id: SUBMISSION_ID, status: 'Accepted' }), stderr: '' }
}
return { stdout: '', stderr: '' }
})
await notarizeDmg(
{ file: f.dmgPath, target: f.dmgTarget, packager: f.packager },
{ run, env: f.signedEnv, sleep: vi.fn(), log: vi.fn() }
)
expect(calls.some(c => c[0] === 'security')).toBe(false)
expect(calls).toContainEqual([
'codesign', '--force', '--sign', SECOND_IDENTITY_HASH, '--timestamp', '--verbose', '--keychain', f.keychainFile, f.dmgPath
])
})
test('DMG notarization shares the remaining combined budget after app notarization and reserves verify headroom', async () => {
const f = await createBuilderFixture()
await signAppWith(f)
const appOutDir = path.join(f.root, 'mac-arm64')
fs.mkdirSync(path.join(appOutDir, `${f.packager.appInfo.productFilename}.app`), { recursive: true })
let elapsed = 0
const calls = []
const run = vi.fn(async (command, args) => {
calls.push([command, ...args])
if (command === 'security') return { stdout: IDENTITY_LIST, stderr: '' }
if (command === 'xcrun' && args[0] === 'notarytool') {
if (args[2].endsWith('.zip')) {
elapsed += 210 * 60 * 1000
}
return { stdout: JSON.stringify({ id: SUBMISSION_ID, status: 'Accepted' }), stderr: '' }
}
return { stdout: '', stderr: '' }
})
await notarize(
{ electronPlatformName: 'darwin', appOutDir, packager: f.packager },
{ run, env: f.signedEnv, sleep: vi.fn(), log: vi.fn(), now: () => elapsed }
)
await notarizeDmg(
{ file: f.dmgPath, target: f.dmgTarget, packager: f.packager },
{ run, env: f.signedEnv, sleep: vi.fn(), log: vi.fn(), now: () => elapsed }
)
const dmgSubmit = calls.find(c => c[0] === 'xcrun' && c[1] === 'notarytool' && c[2] === 'submit' && c[3] === f.dmgPath)
const expectedSeconds = Math.ceil((COMBINED_NOTARY_BUDGET_MS - 210 * 60 * 1000 - DMG_VERIFY_RESERVE_MS) / 1000)
expect(dmgSubmit[dmgSubmit.indexOf('--timeout') + 1]).toBe(`${expectedSeconds}s`)
elapsed = COMBINED_NOTARY_BUDGET_MS - DMG_VERIFY_RESERVE_MS
const exhaustedRun = vi.fn(async command => {
if (command === 'security') return { stdout: IDENTITY_LIST, stderr: '' }
if (command === 'xcrun') throw new Error('notarytool must not run when combined budget is exhausted')
return { stdout: '', stderr: '' }
})
await expect(
notarizeDmg(
{ file: f.dmgPath, target: f.dmgTarget, packager: f.packager },
{ run: exhaustedRun, env: f.signedEnv, sleep: vi.fn(), log: vi.fn(), now: () => elapsed }
)
).rejects.toThrow(/exceeded the wait budget/)
})
test('a build electron-builder left unsigned never signs its DMG with another keychain certificate', async () => {
const cases = [
{ name: 'default keychain, no notary credentials', keychainFile: null, env: {}, expected: 'unsigned' },
{ name: 'default keychain, notary credentials', keychainFile: null, env: 'signed', expected: /without a Developer ID Application signing identity/ },
{ name: 'CSC_LINK keychain', keychainFile: undefined, env: {}, expected: /electron-builder did not sign the app/ }
]
for (const scenario of cases) {
const f = await createBuilderFixture({ keychainFile: scenario.keychainFile })
const run = vi.fn(async command => {
if (command === 'security') return { stdout: TWO_IDENTITY_LIST, stderr: '' }
return { stdout: '', stderr: '' }
})
const done = notarizeDmg(
{ file: f.dmgPath, target: f.dmgTarget, packager: f.packager },
{ run, env: scenario.env === 'signed' ? f.signedEnv : scenario.env, sleep: vi.fn(), log: vi.fn() }
)
if (scenario.expected === 'unsigned') {
await done
} else {
await expect(done, scenario.name).rejects.toThrow(scenario.expected)
}
expect(run.mock.calls.some(([command]) => command === 'codesign'), scenario.name).toBe(false)
expect(fs.readFileSync(f.dmgPath).equals(f.preStapleBytes), scenario.name).toBe(true)
}
})
test('a recorded app signature signs the DMG even when the signing settings would skip an unsigned build', async () => {
for (const env of [{ CSC_IDENTITY_AUTO_DISCOVERY: 'false' }, { CSC_NAME: '-' }]) {
const name = JSON.stringify(env)
const f = await createBuilderFixture()
await signAppWith(f)
const calls = []
const run = vi.fn(async (command, args) => {
calls.push([command, ...args])
if (command === 'xcrun' && args[0] === 'notarytool') {
return { stdout: JSON.stringify({ id: SUBMISSION_ID, status: 'Accepted' }), stderr: '' }
}
return { stdout: '', stderr: '' }
})
await notarizeDmg(
{ file: f.dmgPath, target: f.dmgTarget, packager: f.packager },
{ run, env: { ...f.signedEnv, ...env }, sleep: vi.fn(), log: vi.fn() }
)
expect(calls, name).toContainEqual([
'codesign', '--force', '--sign', IDENTITY_HASH, '--timestamp', '--verbose', '--keychain', f.keychainFile, f.dmgPath
])
expect(calls.some(c => c[0] === 'xcrun' && c[1] === 'notarytool' && c[2] === 'submit'), name).toBe(true)
}
})
test('the DMG notary budget also counts the packing and signing time before afterSign', async () => {
const f = await createBuilderFixture()
await signAppWith(f)
const appOutDir = path.join(f.root, 'mac-arm64')
fs.mkdirSync(path.join(appOutDir, `${f.packager.appInfo.productFilename}.app`), { recursive: true })
let elapsed = 40 * 60 * 1000
const calls = []
const run = vi.fn(async (command, args) => {
calls.push([command, ...args])
if (command === 'xcrun' && args[0] === 'notarytool') {
if (args[2].endsWith('.zip')) elapsed += 210 * 60 * 1000
return { stdout: JSON.stringify({ id: SUBMISSION_ID, status: 'Accepted' }), stderr: '' }
}
return { stdout: '', stderr: '' }
})
const deps = { run, env: f.signedEnv, sleep: vi.fn(), log: vi.fn(), now: () => elapsed }
await notarize({ electronPlatformName: 'darwin', appOutDir, packager: f.packager }, deps)
await notarizeDmg({ file: f.dmgPath, target: f.dmgTarget, packager: f.packager }, deps)
const dmgSubmit = calls.find(c => c[0] === 'xcrun' && c[1] === 'notarytool' && c[2] === 'submit' && c[3] === f.dmgPath)
const expectedSeconds = Math.ceil((COMBINED_NOTARY_BUDGET_MS - 250 * 60 * 1000 - DMG_VERIFY_RESERVE_MS) / 1000)
expect(dmgSubmit[dmgSubmit.indexOf('--timeout') + 1]).toBe(`${expectedSeconds}s`)
})
test('non-DMG artifacts and non-darwin packagers are ignored', async () => {
const f = await createBuilderFixture()
const run = vi.fn()
await notarizeDmg({ file: `${f.dmgPath}.blockmap`, target: f.dmgTarget, packager: f.packager }, { run, env: f.signedEnv })
await notarizeDmg({ file: f.zipPath, target: f.zipTarget, packager: f.packager }, { run, env: f.signedEnv })
await notarizeDmg(
{ file: f.dmgPath, target: f.dmgTarget, packager: { ...f.packager, platform: Platform.LINUX } },
{ run, env: f.signedEnv }
)
expect(run).not.toHaveBeenCalled()
})
test('APPLE_NOTARY_PROFILE auth signs, notarizes, staples, and verifies DMG with --keychain-profile', async () => {
const f = await createBuilderFixture()
await signAppWith(f)
const calls = []
const run = vi.fn(async (command, args) => {
calls.push([command, ...args])
if (command === 'security') return { stdout: IDENTITY_LIST, stderr: '' }
if (command === 'xcrun' && args[0] === 'notarytool') {
return { stdout: JSON.stringify({ id: SUBMISSION_ID, status: 'Accepted' }), stderr: '' }
}
return { stdout: '', stderr: '' }
})
await notarizeDmg(
{ file: f.dmgPath, target: f.dmgTarget, packager: f.packager },
{ run, env: { APPLE_NOTARY_PROFILE: 'release-notary-profile' }, sleep: vi.fn(), log: vi.fn() }
)
const submitCall = calls.find(c => c[0] === 'xcrun' && c[1] === 'notarytool' && c[2] === 'submit')
expect(submitCall).toEqual(expect.arrayContaining(['--keychain-profile', 'release-notary-profile', '--wait']))
expect(calls).toContainEqual(['spctl', '-a', '-vv', '-t', 'open', '--context', 'context:primary-signature', f.dmgPath])
})
test('misconfigured signing or Gatekeeper/stapler validation failures fail loudly', async () => {
const f = await createBuilderFixture({ keychainFile: null })
const noIdentityRun = vi.fn(async () => ({ stdout: ' 0 valid identities found\n', stderr: '' }))
const inlineKey = '-----BEGIN PRIVATE KEY-----\ntest-inline-fixture\n-----END PRIVATE KEY-----'
const beforeTempKeys = new Set(fs.readdirSync(os.tmpdir()).filter(n => n.startsWith('hermes-notary-')))
await expect(
notarizeDmg(
{ file: f.dmgPath, target: f.dmgTarget, packager: f.packager },
{
run: noIdentityRun,
env: {
APPLE_API_KEY: inlineKey,
APPLE_API_KEY_ID: 'KEY123',
APPLE_API_ISSUER: 'ISSUER456',
CSC_IDENTITY_AUTO_DISCOVERY: 'false'
},
sleep: vi.fn(),
log: vi.fn()
}
)
).rejects.toThrow(/without a Developer ID Application signing identity/)
const afterTempKeys = new Set(fs.readdirSync(os.tmpdir()).filter(n => n.startsWith('hermes-notary-')))
expect([...afterTempKeys].filter(n => !beforeTempKeys.has(n))).toEqual([])
await expect(
resolveDmgSigningIdentity(
{ codeSigningInfo: { value: Promise.resolve({ keychainFile: path.join(f.root, 'missing.keychain') }) } },
{ env: {} }
)
).rejects.toThrow(/electron-builder did not sign the app/)
for (const failAt of ['codesign-verify', 'stapler-validate-permanent', 'spctl']) {
const f2 = await createBuilderFixture()
await signAppWith(f2)
const sleep = vi.fn()
const run = vi.fn(async (command, args) => {
if (command === 'security') return { stdout: IDENTITY_LIST, stderr: '' }
if (command === 'codesign' && args.includes('--verify') && failAt === 'codesign-verify') {
throw new Error('code object is not signed at all')
}
if (command === 'xcrun' && args[0] === 'notarytool') {
return { stdout: JSON.stringify({ id: SUBMISSION_ID, status: 'Accepted' }), stderr: '' }
}
if (command === 'xcrun' && args[0] === 'stapler' && args[1] === 'validate' && failAt === 'stapler-validate-permanent') {
throw Object.assign(new Error('The validate action failed! Error 65.'), { code: 65 })
}
if (command === 'spctl' && failAt === 'spctl') {
throw Object.assign(new Error(`${f2.dmgPath}: rejected`), { code: 3 })
}
return { stdout: '', stderr: '' }
})
await expect(
notarizeDmg(
{ file: f2.dmgPath, target: f2.dmgTarget, packager: f2.packager },
{ run, env: f2.signedEnv, sleep, log: vi.fn() }
),
failAt
).rejects.toThrow()
expect(sleep, failAt).not.toHaveBeenCalled()
}
})
test('electron-builder config keeps dmg.sign off and validates artifactBuildCompleted against app-builder-lib schema', async () => {
expect(builderConfig.dmg?.sign).not.toBe(true)
await expect(
validateConfiguration({
...builderConfig,
afterSign: 'scripts/notarize.mjs',
artifactBuildCompleted: 'scripts/notarize-dmg.mjs'
})
).resolves.toBeUndefined()
})
test.runIf(process.platform === 'darwin')('macOS builder config wires both afterSign and outer DMG artifactBuildCompleted hooks', () => {
expect(builderConfig.afterSign).toBe('scripts/notarize.mjs')
expect(builderConfig.artifactBuildCompleted).toBe('scripts/notarize-dmg.mjs')
})

View File

@@ -69,18 +69,78 @@ function resolveApiKeyPath(rawValue) {
}
}
async function submitAndStaple(zipPath, appPath, auth, { run, sleep, log, now }) {
log(`[notarize] submitting ${zipPath}. Waiting for Apple's decision.`)
const deadline = now() + 4 * 60 * 60 * 1000
export function resolveNotaryAuth(env = process.env) {
const profile = String(env.APPLE_NOTARY_PROFILE || '').trim()
if (profile) {
return { auth: ['--keychain-profile', profile], cleanup: () => {} }
}
const keyId = String(env.APPLE_API_KEY_ID || '').trim()
const issuer = String(env.APPLE_API_ISSUER || '').trim()
const rawApiKey = env.APPLE_API_KEY
if (!rawApiKey || !keyId || !issuer) {
return null
}
const key = resolveApiKeyPath(rawApiKey)
return {
auth: ['--key', key.keyPath, '--key-id', keyId, '--issuer', issuer],
cleanup: key.cleanup
}
}
export async function validateStapled(targetPath, {
run = runCommand, sleep = setTimeout, log = console.log, now = () => performance.now(), deadline, label = 'notarize'
} = {}) {
const validateDeadline = Math.min(deadline ?? now() + STAPLE_CONTACT_WINDOW, now() + STAPLE_CONTACT_WINDOW)
let contactRetries = 0
for (let attempt = 1; ; attempt++) {
try {
log(`[${label}] validating stapled ticket (attempt ${attempt})`)
await run('xcrun', ['stapler', 'validate', targetPath], { timeout: 120000 })
return
} catch (error) {
const output = commandOutput(error)
if (!LOST_CONTACT.test(output)) throw error
const delay = contactDelay(contactRetries++)
if (now() + delay >= validateDeadline) throw error
log(`[${label}] lost contact with Apple while validating ${targetPath}. Retrying in ${delay / 1000}s.`)
await sleep(delay)
}
}
}
export const DEFAULT_WAIT_BUDGET_MS = 4 * 60 * 60 * 1000
// The CI Build and package step allows 330 minutes and starts electron-builder in its own process about two minutes
// in. performance.now() counts from that process's start, so packing and signing spend this budget too.
export const COMBINED_NOTARY_BUDGET_MS = 300 * 60 * 1000
export const DMG_VERIFY_RESERVE_MS = 15 * 60 * 1000
export function remainingNotaryBudgetMs({
now = () => performance.now(),
totalBudgetMs = COMBINED_NOTARY_BUDGET_MS,
reserveMs = DMG_VERIFY_RESERVE_MS
} = {}) {
return Math.max(0, totalBudgetMs - now() - reserveMs)
}
export async function submitAndStaple(submitPath, staplePath, auth, {
run = runCommand,
sleep = setTimeout,
log = console.log,
now = () => performance.now(),
label = 'notarize',
waitBudgetMs = DEFAULT_WAIT_BUDGET_MS
}) {
log(`[${label}] submitting ${submitPath}. Waiting for Apple's decision.`)
const deadline = now() + waitBudgetMs
let resumeId
let result
let submitError
for (let attempt = 0; ; attempt++) {
const remaining = Math.ceil(deadline - now())
if (remaining <= 0) {
throw new Error(`Notarization ${resumeId ?? zipPath} exceeded the wait budget`, { cause: submitError })
throw new Error(`Notarization ${resumeId ?? submitPath} exceeded the wait budget`, { cause: submitError })
}
const action = resumeId ? ['wait', resumeId] : ['submit', zipPath, '--wait']
const action = resumeId ? ['wait', resumeId] : ['submit', submitPath, '--wait']
try {
result = await run('xcrun', [
'notarytool', ...action, ...auth, '--timeout', `${Math.ceil(remaining / 1000)}s`, '--output-format', 'json'
@@ -97,7 +157,7 @@ async function submitAndStaple(zipPath, appPath, auth, { run, sleep, log, now })
resumeId ??= output.match(/https:\/\/appstoreconnect\.apple\.com\/notary\/v2\/submissions\/([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})(?=[?\s,}]|$)/i)?.[1]
const delay = contactDelay(attempt)
if (!resumeId || now() + delay >= deadline) break
log(`[notarize] lost contact with Apple while waiting for ${resumeId}. Resuming wait in ${delay / 1000}s.`)
log(`[${label}] lost contact with Apple while waiting for ${resumeId}. Resuming wait in ${delay / 1000}s.`)
await sleep(delay)
}
}
@@ -114,7 +174,7 @@ async function submitAndStaple(zipPath, appPath, auth, { run, sleep, log, now })
if (resumeId && id !== resumeId) {
throw new Error(`notarytool returned submission ${id} while waiting for ${resumeId}`)
}
log(`[notarize] submission ${id}: ${status}`)
log(`[${label}] submission ${id}: ${status}`)
if (submitError || status !== 'Accepted') {
let diagnostics
try {
@@ -133,23 +193,23 @@ async function submitAndStaple(zipPath, appPath, auth, { run, sleep, log, now })
let contactRetries = 0
for (let attempt = 1; ; attempt++) {
try {
log(`[notarize] stapling attempt ${attempt}`)
await run('xcrun', ['stapler', 'staple', '-v', appPath], { timeout: 120000 })
log(`[notarize] ticket stapled for submission ${id}`)
return
log(`[${label}] stapling attempt ${attempt}`)
await run('xcrun', ['stapler', 'staple', '-v', staplePath], { timeout: 120000 })
log(`[${label}] ticket stapled for submission ${id}`)
return { id, deadline }
} catch (error) {
const output = commandOutput(error)
if (error.code === 65 && /CloudKit query[^\n]*Record not found/i.test(output)) {
if (ticketRetries === ticketRetryLimit) throw error
const delay = contactDelay(ticketRetries++)
log(`[notarize] accepted ticket not available. Retrying in ${delay / 1000}s.`)
log(`[${label}] accepted ticket not available. Retrying in ${delay / 1000}s.`)
await sleep(delay)
continue
}
if (!LOST_CONTACT.test(output)) throw error
const delay = contactDelay(contactRetries++)
if (now() + delay >= stapleDeadline) throw error
log(`[notarize] lost contact with Apple while stapling ${id}. Retrying in ${delay / 1000}s.`)
log(`[${label}] lost contact with Apple while stapling ${id}. Retrying in ${delay / 1000}s.`)
await sleep(delay)
}
}
@@ -167,25 +227,14 @@ export default async function notarize(context, {
throw new Error(`Cannot notarize missing app bundle: ${appPath}`)
}
const profile = String(env.APPLE_NOTARY_PROFILE || '').trim()
let auth
let cleanup = () => {}
if (profile) {
auth = ['--keychain-profile', profile]
} else {
const keyId = String(env.APPLE_API_KEY_ID || '').trim()
const issuer = String(env.APPLE_API_ISSUER || '').trim()
const rawApiKey = env.APPLE_API_KEY
if (!rawApiKey || !keyId || !issuer) {
log(
'Skipping notarization: APPLE_API_KEY, APPLE_API_KEY_ID, and APPLE_API_ISSUER are not fully configured.'
)
return
}
const key = resolveApiKeyPath(rawApiKey)
auth = ['--key', key.keyPath, '--key-id', keyId, '--issuer', issuer]
cleanup = key.cleanup
const resolved = resolveNotaryAuth(env)
if (!resolved) {
log(
'Skipping notarization: APPLE_API_KEY, APPLE_API_KEY_ID, and APPLE_API_ISSUER are not fully configured.'
)
return
}
const { auth, cleanup } = resolved
const zipPath = path.join(appOutDir, `${appName}.zip`)
try {

View File

@@ -252,6 +252,7 @@ export function buildStampPayload(stamp, env = process.env, platform = process.p
base.displayVersion = channelBuild.version
}
if (variant === 'bundled') base.receiverProtocol = 1
if (variant === 'bundled' && platform === 'darwin') base.signedDmg = true
const updateMechanism = {
'': 'self',

View File

@@ -2,6 +2,8 @@
from __future__ import annotations
import argparse
import base64
import gzip
import hashlib
import json
import os
@@ -54,6 +56,85 @@ def sha256_file(file: Path) -> str:
return hashlib.file_digest(handle, "sha256").hexdigest()
def _sha512_base64(file: Path) -> str:
with file.open("rb") as handle:
return base64.b64encode(hashlib.file_digest(handle, "sha512").digest()).decode("ascii")
def _verify_blockmap_size(artifact: Path) -> None:
blockmap = artifact.with_name(artifact.name + ".blockmap")
if not blockmap.is_file():
raise ValueError(f"Missing DMG blockmap: {blockmap.name}")
try:
data = json.loads(gzip.decompress(blockmap.read_bytes()))
except (OSError, gzip.BadGzipFile, json.JSONDecodeError) as exc:
raise ValueError(f"Invalid DMG blockmap: {blockmap.name}") from exc
files = data.get("files") if isinstance(data, dict) else None
if not isinstance(files, list) or len(files) != 1 or not isinstance(files[0], dict):
raise ValueError(f"Invalid DMG blockmap structure: {blockmap.name}")
sizes = files[0].get("sizes")
if not isinstance(sizes, list) or any(type(item) is not int or item < 0 for item in sizes):
raise ValueError(f"Invalid DMG blockmap chunk sizes: {blockmap.name}")
actual_size = artifact.stat().st_size
if sum(sizes) != actual_size:
raise ValueError(
f"DMG blockmap covers {sum(sizes)} bytes, but {artifact.name} is {actual_size} bytes"
)
def _require_feed_entry(feed_name: str, entries: list[dict], artifact: Path) -> None:
matches = [entry for entry in entries if entry.get("url") == artifact.name]
if len(matches) != 1:
raise ValueError(
f"macOS feed {feed_name} must list exactly one entry for {artifact.name}, found {len(matches)}"
)
entry = matches[0]
if entry.get("size") != artifact.stat().st_size or entry.get("sha512") != _sha512_base64(artifact):
raise ValueError(f"macOS feed {feed_name} disagrees with {artifact.name} on disk")
def _verify_mac_feed_dmg(root: Path, package: Path, dmg: Path, *, expect_feed: bool) -> None:
feeds = sorted(root.glob("*-mac.yml"))
if not feeds:
if expect_feed:
raise ValueError(f"Missing macOS update feed for {dmg.name}")
return
from scripts.releases.darwin import parse_mac_feed
for feed_path in feeds:
parsed = parse_mac_feed(feed_path.read_text(encoding="utf-8-sig"))
_require_feed_entry(feed_path.name, parsed["files"], package)
_require_feed_entry(feed_path.name, parsed["files"], dmg)
def _verify_macos_dmg(
root: Path,
arch: str,
package: Path,
expected_team: str,
*,
expect_feed: bool,
) -> None:
dmg = single(root.glob(f"*-mac-{arch}.dmg"))
expected_name = package.name.removesuffix(".zip") + ".dmg"
if dmg.name != expected_name:
raise ValueError("macOS DMG filename differs from requested version")
subprocess.run(["codesign", "--verify", "--verbose=2", str(dmg)], check=True, timeout=60)
signature = subprocess.run(
["codesign", "-dv", "--verbose=4", str(dmg)],
check=True,
capture_output=True,
text=True,
encoding="utf-8",
timeout=60,
)
dmg_team = re.search(r"^TeamIdentifier=([A-Z0-9]{10})$", signature.stderr, re.MULTILINE)
if not dmg_team or dmg_team.group(1) != expected_team:
raise ValueError("Signed DMG team differs from signed app")
_verify_blockmap_size(dmg)
_verify_mac_feed_dmg(root, package, dmg, expect_feed=expect_feed)
def stamp_matches(stamp: dict, tag: str, commit: str, *, channel_request: dict | None = None,
legacy_commit_build: bool = False) -> None:
if channel_request is not None and channel_request.get("receiverCandidate"):
@@ -165,6 +246,72 @@ def _packaged_windows_executable_version(
return probe(extracted)
def _record_macos(
root: Path,
arch: str,
tag: str,
commit: str,
*,
expected_version: str | None,
channel_request: dict | None,
legacy_commit_build: bool,
) -> dict:
version = (
channel_request["version"]
if channel_request is not None
else expected_version if legacy_commit_build else release_version(tag)
)
package = single(root.glob(f"*-mac-{arch}.zip"))
if not package.name.endswith(f"-{version}-mac-{arch}.zip"):
raise ValueError("macOS artifact filename differs from requested version")
require_squirrel_downloadable(package)
app = single(root.glob("mac*/*.app"))
subprocess.run(["codesign", "--verify", "--strict", str(app)], check=True, timeout=60)
signature = subprocess.run(
["codesign", "-dv", "--verbose=4", str(app)],
check=True,
capture_output=True,
text=True,
encoding="utf-8",
timeout=60,
)
team = re.search(r"^TeamIdentifier=([A-Z0-9]{10})$", signature.stderr, re.MULTILINE)
if not team:
raise ValueError("Signed app has no Developer ID team")
with zipfile.ZipFile(package) as archive:
require_owner_write(archive)
info = plistlib.loads(archive.read(single(
n for n in archive.namelist() if re.fullmatch(r"[^/]+\.app/Contents/Info\.plist", n)
)))
stamp = json.loads(archive.read(single(
n for n in archive.namelist() if re.fullmatch(r"[^/]+\.app/Contents/Resources/install-stamp\.json", n)
)))
stamp_matches(stamp, tag, commit, channel_request=channel_request,
legacy_commit_build=legacy_commit_build)
from hermes_cli.update_channel import is_commit_tag
is_commit = channel_request is None and is_commit_tag(tag)
if not is_commit or (not legacy_commit_build and stamp.get("signedDmg") is True):
_verify_macos_dmg(
root,
arch,
package,
team.group(1),
expect_feed=channel_request is None and not is_commit,
)
fields: dict = {
"identity": info["CFBundleIdentifier"],
"teamId": team.group(1),
"version": info["CFBundleShortVersionString"],
"filename": package.name,
}
if stamp.get("receiverProtocol") == 1:
fields["receiverProtocol"] = 1
if fields["version"] != version:
raise ValueError("App version differs from requested version")
return fields
def _record_termux(root: Path, tag: str, commit: str, *, legacy_commit_build: bool) -> dict:
from hermes_cli.update_channel import is_commit_tag, tag_core
@@ -237,29 +384,12 @@ def record(platform: str, arch: str, root: Path, tag: str, commit: str, out: Pat
if stamp.get("receiverProtocol") == 1:
row["receiverProtocol"] = 1
elif platform == "macos":
version = (channel_request["version"] if channel_request is not None
else expected_version if legacy_commit_build else release_version(tag))
package = single(root.glob(f"*-mac-{arch}.zip"))
if not package.name.endswith(f"-{version}-mac-{arch}.zip"):
raise ValueError("macOS artifact filename differs from requested version")
require_squirrel_downloadable(package)
app = single(root.glob("mac*/*.app"))
subprocess.run(["codesign", "--verify", "--strict", str(app)], check=True)
signature = subprocess.run(["codesign", "-dv", "--verbose=4", str(app)], check=True, capture_output=True, text=True, encoding="utf-8")
team = re.search(r"^TeamIdentifier=([A-Z0-9]{10})$", signature.stderr, re.MULTILINE)
if not team:
raise ValueError("Signed app has no Developer ID team")
with zipfile.ZipFile(package) as archive:
require_owner_write(archive)
info = plistlib.loads(archive.read(single(n for n in archive.namelist() if re.fullmatch(r"[^/]+\.app/Contents/Info.plist", n))))
stamp = json.loads(archive.read(single(n for n in archive.namelist() if re.fullmatch(r"[^/]+\.app/Contents/Resources/install-stamp.json", n))))
stamp_matches(stamp, tag, commit, channel_request=channel_request,
legacy_commit_build=legacy_commit_build)
if stamp.get("receiverProtocol") == 1:
row["receiverProtocol"] = 1
row.update(identity=info["CFBundleIdentifier"], teamId=team.group(1), version=info["CFBundleShortVersionString"], filename=package.name)
if row["version"] != version:
raise ValueError("App version differs from requested version")
row.update(_record_macos(
root, arch, tag, commit,
expected_version=expected_version,
channel_request=channel_request,
legacy_commit_build=legacy_commit_build,
))
elif platform == "termux":
row.update(_record_termux(root, tag, commit, legacy_commit_build=legacy_commit_build))
else:

View File

@@ -3,7 +3,7 @@ import fs from 'node:fs'
import os from 'node:os'
import path from 'node:path'
import { execFileSync, spawnSync } from 'node:child_process'
import { bundleIdentity, verifyBundleStamp, verifyMacMetadata } from '../tests/install/e2e-assets/bundle-smoke-metadata.mjs'
import { bundleIdentity, shouldVerifyMacDmg, verifyBundleStamp, verifyMacDmg, verifyMacMetadata } from '../tests/install/e2e-assets/bundle-smoke-metadata.mjs'
import { stampAssertions } from '../tests/install/e2e-assets/mac-bundled-manifest.cjs'
import { randomBytes } from 'node:crypto'
import { buildStampPayload } from '../apps/desktop/scripts/write-build-stamp.mjs'
@@ -135,6 +135,60 @@ test('workspace admission rejects reuse and symlink escapes before creating anyt
} finally { fs.rmSync(temp, { recursive: true, force: true }) }
})
test('shouldVerifyMacDmg enforces outer DMG checks on all releases/channels and signedDmg commit claims while allowing older commit claims', () => {
expect(shouldVerifyMacDmg({ tag: 'v1.2.3', stamp: {} })).toBe(true)
expect(shouldVerifyMacDmg({ tag: 'canary.20261125T000000Z-v1.2.3', stamp: {} })).toBe(true)
expect(shouldVerifyMacDmg({ channelRequest: { channel: 'preview' }, stamp: {} })).toBe(true)
expect(shouldVerifyMacDmg({ tag: 'commit.20261125T000000Z-v1.2.3', stamp: { signedDmg: true } })).toBe(true)
expect(shouldVerifyMacDmg({ tag: '', stamp: { signedDmg: true } })).toBe(true)
expect(shouldVerifyMacDmg({ tag: 'commit.20261125T000000Z-v1.2.3', stamp: {} })).toBe(false)
expect(shouldVerifyMacDmg({ tag: '', stamp: {} })).toBe(false)
const commit = 'b'.repeat(40)
const runtime = { commands: { hermes: 'bin/hermes' } }
expect(buildStampPayload({ commit, dirty: false }, { HERMES_DESKTOP_VARIANT: 'bundled' }, 'darwin', { runtime }).signedDmg).toBe(true)
expect(buildStampPayload({ commit, dirty: false }, { HERMES_DESKTOP_VARIANT: 'bundled' }, 'win32', { runtime }).signedDmg).toBeUndefined()
expect(buildStampPayload({ commit, dirty: false }, { HERMES_DESKTOP_VARIANT: 'light' }, 'darwin', { runtime }).signedDmg).toBeUndefined()
})
test('verifyMacDmg enforces codesign, team ID, stapler ticket, and spctl primary-signature open policy', () => {
const temp = fs.mkdtempSync(path.join(os.tmpdir(), 'dmg-smoke-'))
try {
const dmg = path.join(temp, 'HermesBundled-1.2.3-mac-arm64.dmg')
fs.writeFileSync(dmg, 'dmg-fixture')
const calls = []
const exec = (cmd, args) => { calls.push([cmd, ...args]) }
const spawn = (cmd, args) => {
calls.push([cmd, ...args])
return { status: 0, stderr: 'Authority=Developer ID Application: Nous Research (TEAM123456)\nTeamIdentifier=TEAM123456\n' }
}
expect(verifyMacDmg(dmg, { exec, spawn })).toEqual({ dmg, teamIdentifier: 'TEAM123456' })
expect(calls).toEqual([
['/usr/bin/codesign', '--verify', '--verbose=2', dmg],
['/usr/bin/codesign', '-dv', '--verbose=4', dmg],
['/usr/bin/xcrun', 'stapler', 'validate', dmg],
['/usr/sbin/spctl', '-a', '-vv', '-t', 'open', '--context', 'context:primary-signature', dmg],
])
expect(() => verifyMacDmg(path.join(temp, 'missing.dmg'), { exec, spawn })).toThrow(/existing \.dmg/)
expect(() => verifyMacDmg(path.join(temp, 'app.zip'), { exec, spawn })).toThrow(/existing \.dmg/)
expect(() => verifyMacDmg(dmg, {
exec,
spawn: () => ({ status: 0, stderr: 'TeamIdentifier=not set\n' }),
})).toThrow(/signing team/)
expect(() => verifyMacDmg(dmg, {
exec,
spawn: () => ({ status: 1, stderr: 'code object is not signed at all' }),
})).toThrow(/codesign display failed/)
expect(() => verifyMacDmg(dmg, {
exec: (cmd) => { if (cmd === '/usr/sbin/spctl') throw new Error('rejected') },
spawn,
})).toThrow(/rejected/)
} finally {
fs.rmSync(temp, { recursive: true, force: true })
}
})
test.runIf(process.platform === 'win32')('PowerShell admits only the pinned package and native slice', () => {
const script = path.resolve(import.meta.dirname, '../tests/install/e2e-assets/windows-bundle-metadata.test.ps1')
expect(execFileSync('powershell.exe', ['-NoProfile', '-ExecutionPolicy', 'Bypass', '-File', script],

View File

@@ -7,6 +7,8 @@ qualification. No admission, metadata recorder or channel publisher is mocked.
"""
from __future__ import annotations
import base64
import gzip
import hashlib
import json
import os
@@ -134,12 +136,31 @@ def native_leg(root, identity, env, platform, arch):
else:
name = f"{artifact}-{version}-mac-{arch}"
(root / f"mac-{arch}/{artifact}.app").mkdir(parents=True)
with zipfile.ZipFile(root / f"{name}.zip", "w") as package:
zip_path = root / f"{name}.zip"
with zipfile.ZipFile(zip_path, "w") as package:
package.writestr(f"{artifact}.app/Contents/Info.plist", plistlib.dumps({"CFBundleIdentifier": identity["appId"], "CFBundleShortVersionString": version}))
package.writestr(f"{artifact}.app/Contents/Resources/install-stamp.json", json.dumps(stamp))
(root / "canary-mac.yml").write_text(json.dumps({"version": version}))
for suffix in ("dmg", "dmg.blockmap", "zip.blockmap"):
(root / f"{name}.{suffix}").write_bytes(b"unsigned transport fixture")
dmg_bytes = b"unsigned transport fixture"
dmg_path = root / f"{name}.dmg"
dmg_path.write_bytes(dmg_bytes)
blockmap = gzip.compress(json.dumps({
"version": "2",
"files": [{"name": "file", "offset": 0, "checksums": ["fixture"], "sizes": [len(dmg_bytes)]}],
}).encode("utf-8"))
(root / f"{name}.dmg.blockmap").write_bytes(blockmap)
(root / f"{name}.zip.blockmap").write_bytes(b"unsigned transport fixture")
zip_bytes = zip_path.read_bytes()
zip_sha = base64.b64encode(hashlib.sha512(zip_bytes).digest()).decode("ascii")
dmg_sha = base64.b64encode(hashlib.sha512(dmg_bytes).digest()).decode("ascii")
(root / "canary-mac.yml").write_text(hermes_yaml.safe_dump({
"version": version or "0.0.0",
"files": [
{"url": zip_path.name, "sha512": zip_sha, "size": len(zip_bytes)},
{"url": dmg_path.name, "sha512": dmg_sha, "size": len(dmg_bytes)},
],
"path": zip_path.name,
"sha512": zip_sha,
}, sort_keys=False))
@pytest.mark.parametrize("platform", ["win32", "darwin"])

View File

@@ -81,6 +81,27 @@ export function verifyMacMetadata(plist, stamp, { commit, tag, channelRequest })
return version
}
export function shouldVerifyMacDmg({ tag = '', channelRequest = null, stamp = null } = {}) {
const isCommitBuild = channelRequest === null && (!tag || COMMIT_TAG_RE.test(tag))
return isCommitBuild ? stamp?.signedDmg === true : true
}
export function verifyMacDmg(dmg, { exec = execFileSync, spawn = spawnSync } = {}) {
if (!dmg || !dmg.endsWith('.dmg') || !fs.existsSync(dmg)) {
throw new Error(`Expected an existing .dmg artifact: ${dmg || '(none)'}`)
}
exec('/usr/bin/codesign', ['--verify', '--verbose=2', dmg], { stdio: 'inherit' })
const display = spawn('/usr/bin/codesign', ['-dv', '--verbose=4', dmg], { encoding: 'utf8' })
if (display.error || display.status !== 0) {
throw new Error(`codesign display failed: ${display.error || display.stderr}`)
}
const signedTeam = codesignTeam(display.stderr)
if (!/^[A-Z0-9]{10}$/.test(signedTeam || '')) throw new Error('DMG has no valid signing team')
exec('/usr/bin/xcrun', ['stapler', 'validate', dmg], { stdio: 'inherit' })
exec('/usr/sbin/spctl', ['-a', '-vv', '-t', 'open', '--context', 'context:primary-signature', dmg], { stdio: 'inherit' })
return { dmg, teamIdentifier: signedTeam }
}
function verifyMac(app, commit, tag, arch, channelRequest) {
const expected = bundleIdentity(commit, tag, channelRequest)
@@ -134,7 +155,7 @@ function prepareDirectories(work, out) {
function main() {
const [command, ...args] = process.argv.slice(2)
const { values } = parseArgs({ args, options: Object.fromEntries(
['commit', 'tag', 'platform', 'stamp', 'app', 'arch', 'out', 'work', 'channel-request'].map(key => [key, { type: 'string' }])) })
['commit', 'tag', 'platform', 'stamp', 'app', 'dmg', 'identity', 'arch', 'out', 'work', 'channel-request'].map(key => [key, { type: 'string' }])) })
if (values['channel-request'] !== undefined) {
// Preserve the raw JSON for the protocol decoder's duplicate-key checks.
const raw = fs.readFileSync(values['channel-request'], 'utf8')
@@ -146,6 +167,11 @@ function main() {
identity: () => bundleIdentity(values.commit, values.tag, values.channelRequest),
stamp: () => verifyBundleStamp(JSON.parse(fs.readFileSync(values.stamp, 'utf8')), values),
'verify-mac': () => verifyMac(values.app, values.commit, values.tag, values.arch, values.channelRequest),
'verify-mac-dmg': () => verifyMacDmg(values.dmg),
'should-verify-mac-dmg': () => {
const installed = values.identity ? JSON.parse(fs.readFileSync(values.identity, 'utf8')) : null
return { verifyMacDmg: shouldVerifyMacDmg({ tag: values.tag, channelRequest: values.channelRequest ?? null, stamp: installed?.stamp ?? null }) }
},
prepare: () => prepareDirectories(values.work, values.out),
}
if (!commands[command]) throw new Error(`Unknown command: ${command}`)

View File

@@ -49,8 +49,21 @@ trap 'exit 143' TERM
/usr/bin/shasum -a 256 "$artifact" > "$out/artifact-before.sha256"
mkdir "$work/install" "$work/home" "$work/user-data"
shopt -s nullglob
# The driver owns which artifacts need the outer DMG check. Asked before install it has no stamp yet, so it
# answers for releases and channels and leaves commit claims to the installed app's stamp. The assignment keeps a
# driver failure fatal under set -e.
dmg_check_needed() {
need_dmg_verify=$("$node" "$metadata" should-verify-mac-dmg "${identity_args[@]}" "$@" \
| "$node" -e 'console.log(JSON.parse(require("fs").readFileSync(0,"utf8")).verifyMacDmg ? "1" : "0")')
}
dmg_verified=0
case "$artifact" in
*.dmg)
dmg_check_needed
if [[ $need_dmg_verify == 1 ]]; then
"$node" "$metadata" verify-mac-dmg --dmg "$artifact" --out "$out/dmg-identity.json"
dmg_verified=1
fi
mountpoint=$work/mount
mkdir "$mountpoint"
/usr/bin/hdiutil attach -readonly -nobrowse -noautoopen -mountpoint "$mountpoint" "$artifact"
@@ -68,6 +81,19 @@ apps=("$work/install"/*.app)
((${#apps[@]} == 1)) || fail 'Installed artifact must contain exactly one top-level .app'
[[ -d ${apps[0]} && ! -L ${apps[0]} ]] || fail 'Installed application must not be a link'
"$node" "$metadata" verify-mac --app "${apps[0]}" --arch "$arch" "${identity_args[@]}" --out "$out/installed-identity.json"
if [[ $artifact == *.dmg ]]; then
if ((dmg_verified == 0)); then
dmg_check_needed --identity "$out/installed-identity.json"
if [[ $need_dmg_verify == 1 ]]; then
"$node" "$metadata" verify-mac-dmg --dmg "$artifact" --out "$out/dmg-identity.json"
dmg_verified=1
fi
fi
if ((dmg_verified == 1)); then
"$node" -e 'const d = require(process.argv[1]), a = require(process.argv[2]); if (d.teamIdentifier !== a.teamIdentifier) throw new Error(`DMG signing team ${d.teamIdentifier} disagrees with app team ${a.teamIdentifier}`)' \
"$out/dmg-identity.json" "$out/installed-identity.json"
fi
fi
exe=$("$node" -e 'console.log(require(process.argv[1]).exe)' "$out/installed-identity.json")
root=$("$node" -e 'console.log(require(process.argv[1]).root)' "$out/installed-identity.json")
/usr/bin/shasum -a 256 "$artifact" > "$out/artifact-after.sha256"

View File

@@ -1,12 +1,16 @@
"""Native artifact metadata stays bound to tagged or tagless package inputs."""
from __future__ import annotations
import base64
import gzip
import hashlib
import json
import plistlib
import stat
import subprocess
import zipfile
import hermes_yaml
import pytest
from scripts.bundles import release_artifacts
@@ -36,6 +40,7 @@ def test_macos_record_binds_filename_version_and_provenance(tmp_path, monkeypatc
}))
archive.writestr("Product.app/Contents/Resources/install-stamp.json",
json.dumps(package_stamp))
_add_outer_dmg(root, package, feed=not channel)
def codesign(argv, **kwargs):
assert argv[0] == "codesign"
@@ -102,6 +107,7 @@ def record_mac_update(tmp_path, monkeypatch, extra=(), size=None):
grown.truncate(size - len(data))
grown.seek(size - len(data))
grown.write(data)
_add_outer_dmg(root, package, feed=True)
monkeypatch.setattr(release_artifacts.subprocess, "run", lambda argv, **kwargs: subprocess.CompletedProcess(
argv, 0, stderr="TeamIdentifier=ABCDEFGHIJ\n"))
out = root / "metadata.json"
@@ -142,3 +148,220 @@ def test_macos_record_refuses_an_update_zip_squirrel_cannot_download(tmp_path, m
def test_macos_record_accepts_an_update_zip_just_under_one_gib(tmp_path, monkeypatch):
out = record_mac_update(tmp_path, monkeypatch, size=release_artifacts.SQUIRREL_ZIP_LIMIT - 1)
assert json.loads(out.read_text(encoding="utf-8"))["version"] == "1.2.3"
def _write_blockmap(path, total_size: int) -> None:
payload = {"version": "2", "files": [{"name": "file", "offset": 0, "checksums": ["abc"], "sizes": [total_size]}]}
path.write_bytes(gzip.compress(json.dumps(payload).encode("utf-8")))
def _sha512_base64(path) -> str:
with path.open("rb") as handle: # streamed: the Squirrel-limit fixtures are a sparse 1 GiB ZIP
return base64.b64encode(hashlib.file_digest(handle, "sha512").digest()).decode("ascii")
def _write_mac_feed(path, version: str, zip_path, dmg_path, *, dmg_size: int | None = None, dmg_sha512: str | None = None) -> None:
zip_sha = _sha512_base64(zip_path)
feed = {
"version": version,
"files": [
{"url": zip_path.name, "sha512": zip_sha, "size": zip_path.stat().st_size},
{"url": dmg_path.name, "sha512": dmg_sha512 or _sha512_base64(dmg_path),
"size": dmg_path.stat().st_size if dmg_size is None else dmg_size},
],
"path": zip_path.name,
"sha512": zip_sha,
}
path.write_text(hermes_yaml.safe_dump(feed, sort_keys=False), encoding="utf-8")
def _add_outer_dmg(root, package, *, feed: bool) -> None:
"""The signed DMG (and, for tagged releases, the feed) a record needs beside its update ZIP."""
dmg = package.with_suffix(".dmg")
dmg.write_bytes(b"signed-stapled-dmg")
_write_blockmap(dmg.with_name(dmg.name + ".blockmap"), dmg.stat().st_size)
if feed:
_write_mac_feed(root / "stable-mac.yml", "1.2.3", package, dmg)
def test_macos_record_verifies_outer_dmg_signature_blockmap_and_feed_consistency(tmp_path, monkeypatch):
commit, root = "a" * 40, tmp_path / "release"
(root / "mac" / "Product.app").mkdir(parents=True)
package = root / "Product-1.2.3-mac-arm64.zip"
dmg = root / "Product-1.2.3-mac-arm64.dmg"
blockmap = root / "Product-1.2.3-mac-arm64.dmg.blockmap"
feed = root / "arm64-stable-mac.yml"
out = root / "metadata-macos-arm64.json"
with zipfile.ZipFile(package, "w") as archive:
archive.writestr("Product.app/Contents/Info.plist", plistlib.dumps({
"CFBundleIdentifier": "ai.hermes.test", "CFBundleShortVersionString": "1.2.3",
}))
archive.writestr("Product.app/Contents/Resources/install-stamp.json",
json.dumps({"commit": commit, "tag": "v1.2.3", "baseVersion": "1.2.3"}))
pre_staple = b"udif-dmg-unsigned-bytes"
post_staple = pre_staple + b"-codesign-cms-and-stapled-ticket"
dmg.write_bytes(post_staple)
_write_blockmap(blockmap, len(post_staple))
_write_mac_feed(feed, "1.2.3", package, dmg)
calls: list[list[str]] = []
teams = {"app": "ABCDEFGHIJ", "dmg": "ABCDEFGHIJ"}
def fake_codesign(argv, **kwargs):
calls.append(list(argv))
assert argv[0] == "codesign"
target = argv[-1]
team_id = teams["dmg"] if target.endswith(".dmg") else teams["app"]
return subprocess.CompletedProcess(argv, 0, stderr=f"TeamIdentifier={team_id}\n")
monkeypatch.setattr(release_artifacts.subprocess, "run", fake_codesign)
release_artifacts.record("macos", "arm64", root, "v1.2.3", commit, out)
assert ["codesign", "--verify", "--verbose=2", str(dmg)] in calls
assert ["codesign", "-dv", "--verbose=4", str(dmg)] in calls
_write_blockmap(blockmap, len(pre_staple))
with pytest.raises(ValueError, match="blockmap"):
release_artifacts.record("macos", "arm64", root, "v1.2.3", commit, out)
_write_blockmap(blockmap, len(post_staple))
_write_mac_feed(feed, "1.2.3", package, dmg, dmg_size=len(pre_staple))
with pytest.raises(ValueError, match="feed"):
release_artifacts.record("macos", "arm64", root, "v1.2.3", commit, out)
pre_sha = base64.b64encode(hashlib.sha512(pre_staple).digest()).decode("ascii")
_write_mac_feed(feed, "1.2.3", package, dmg, dmg_size=len(post_staple), dmg_sha512=pre_sha)
with pytest.raises(ValueError, match="feed"):
release_artifacts.record("macos", "arm64", root, "v1.2.3", commit, out)
zip_bytes = package.read_bytes()
zip_sha = base64.b64encode(hashlib.sha512(zip_bytes).digest()).decode("ascii")
feed.write_text(hermes_yaml.safe_dump({
"version": "1.2.3",
"files": [{"url": package.name, "sha512": zip_sha, "size": len(zip_bytes)}],
"path": package.name,
"sha512": zip_sha,
}, sort_keys=False), encoding="utf-8")
with pytest.raises(ValueError, match="must list exactly one entry"):
release_artifacts.record("macos", "arm64", root, "v1.2.3", commit, out)
_write_mac_feed(feed, "1.2.3", package, dmg)
blockmap.unlink()
with pytest.raises(ValueError, match="Missing DMG blockmap"):
release_artifacts.record("macos", "arm64", root, "v1.2.3", commit, out)
_write_blockmap(blockmap, len(post_staple))
feed.unlink()
with pytest.raises(ValueError, match="Missing macOS update feed"):
release_artifacts.record("macos", "arm64", root, "v1.2.3", commit, out)
_write_mac_feed(feed, "1.2.3", package, dmg)
teams["dmg"] = "ZZZZZZZZZZ"
with pytest.raises(ValueError, match="team"):
release_artifacts.record("macos", "arm64", root, "v1.2.3", commit, out)
teams["dmg"] = "ABCDEFGHIJ"
wrong_dmg = root / "Product-9.9.9-mac-arm64.dmg"
dmg.rename(wrong_dmg)
with pytest.raises(ValueError, match="filename"):
release_artifacts.record("macos", "arm64", root, "v1.2.3", commit, out)
wrong_dmg.unlink()
with pytest.raises(ValueError, match="Expected exactly one artifact"):
release_artifacts.record("macos", "arm64", root, "v1.2.3", commit, out)
def test_macos_record_matches_commit_claim_dmg_contract_for_new_pre_pr_and_legacy_commits(tmp_path, monkeypatch):
commit = "a" * 40
claim_tag = "commit.20261125T000000Z-v1.2.3"
def make_root(name: str, *, stamp: dict, version: str, with_blockmap: bool):
root = tmp_path / name
(root / "mac" / "Product.app").mkdir(parents=True)
package = root / f"Product-{version}-mac-arm64.zip"
dmg = root / f"Product-{version}-mac-arm64.dmg"
with zipfile.ZipFile(package, "w") as archive:
archive.writestr("Product.app/Contents/Info.plist", plistlib.dumps({
"CFBundleIdentifier": "ai.hermes.test", "CFBundleShortVersionString": version,
}))
archive.writestr("Product.app/Contents/Resources/install-stamp.json", json.dumps(stamp))
dmg.write_bytes(b"commit-dmg-bytes")
if with_blockmap:
_write_blockmap(root / f"{dmg.name}.blockmap", dmg.stat().st_size)
return root, dmg
calls: list[str] = []
def codesign(argv, **kwargs):
calls.append(argv[-1])
return subprocess.CompletedProcess(argv, 0, stderr="TeamIdentifier=ABCDEFGHIJ\n")
monkeypatch.setattr(release_artifacts.subprocess, "run", codesign)
# New commit claim (signedDmg: true) enforces outer DMG + blockmap without requiring a feed yml.
claim_version = "1.2.3+commit.20261125T000000Z"
new_root, new_dmg = make_root(
"new-claim",
stamp={"source": "commit-build", "commit": commit, "tag": claim_tag, "baseVersion": claim_version, "signedDmg": True},
version=claim_version,
with_blockmap=True,
)
release_artifacts.record("macos", "arm64", new_root, claim_tag, commit, new_root / "meta.json")
assert str(new_dmg) in calls
(new_root / f"{new_dmg.name}.blockmap").unlink()
with pytest.raises(ValueError, match="Missing DMG blockmap"):
release_artifacts.record("macos", "arm64", new_root, claim_tag, commit, new_root / "meta.json")
# Pre-PR claim-aware commit (signedDmg absent) and legacy commit both skip outer DMG while checking .app.
calls.clear()
pre_pr_root, pre_pr_dmg = make_root(
"pre-pr-claim",
stamp={"source": "commit-build", "commit": commit, "tag": claim_tag, "baseVersion": claim_version},
version=claim_version,
with_blockmap=False,
)
release_artifacts.record("macos", "arm64", pre_pr_root, claim_tag, commit, pre_pr_root / "meta.json")
assert str(pre_pr_dmg) not in calls
legacy_root, legacy_dmg = make_root(
"legacy-claim",
stamp={"source": "commit-build", "commit": commit, "tag": None, "baseVersion": "1.2.3"},
version="1.2.3",
with_blockmap=False,
)
release_artifacts.record(
"macos", "arm64", legacy_root, claim_tag, commit, legacy_root / "meta.json", legacy_commit_build=True,
)
assert str(legacy_dmg) not in calls
assert json.loads((legacy_root / "meta.json").read_text(encoding="utf-8"))["legacyCommitBuild"] is True
@pytest.mark.parametrize("kind", ["tagged", "channel", "signed commit claim"])
def test_macos_record_refuses_a_root_without_its_outer_dmg(tmp_path, monkeypatch, kind):
"""A record that must check the outer DMG fails closed when the root holds only the update ZIP."""
commit = "a" * 40
request = channel_request(commit, sequence=6) if kind == "channel" else None
tag, version, stamp = {
"tagged": ("v1.2.3", "1.2.3", {"commit": commit, "tag": "v1.2.3", "baseVersion": "1.2.3"}),
"channel": (None, request and request["version"],
{"source": "channel-build", "channelBuild": request, "commit": commit, "tag": None}),
"signed commit claim": ("commit.20261125T000000Z-v1.2.3", "1.2.3+commit.20261125T000000Z", {
"source": "commit-build", "commit": commit, "tag": "commit.20261125T000000Z-v1.2.3",
"baseVersion": "1.2.3+commit.20261125T000000Z", "signedDmg": True,
}),
}[kind]
root = tmp_path / "release"
(root / "mac" / "Product.app").mkdir(parents=True)
with zipfile.ZipFile(root / f"Product-{version}-mac-arm64.zip", "w") as archive:
archive.writestr("Product.app/Contents/Info.plist", plistlib.dumps({
"CFBundleIdentifier": request["identity"]["appId"] if request else "ai.hermes.test",
"CFBundleShortVersionString": version,
}))
archive.writestr("Product.app/Contents/Resources/install-stamp.json", json.dumps(stamp))
monkeypatch.setattr(release_artifacts.subprocess, "run", lambda argv, **kwargs: subprocess.CompletedProcess(
argv, 0, stderr="TeamIdentifier=ABCDEFGHIJ\n"))
out = root / "metadata.json"
with pytest.raises(ValueError, match="Expected exactly one artifact"):
release_artifacts.record("macos", "arm64", root, tag, commit, out, channel_request=request)
assert not out.exists()

View File

@@ -70,9 +70,13 @@ The existing `release-signing` environment supplies:
`CLOUDFLARE_R2_SECRET_ACCESS_KEY`: bucket access secrets.
- `CLOUDFLARE_R2_BUCKET`, `CLOUDFLARE_R2_PUBLIC_URL`: repository/environment vars.
Publishing requires the Apple credentials. The existing after-sign hook owns
notarization, so electron-builder's second notarization path is disabled.
The publish gate verifies the signature, stapled ticket and Gatekeeper assessment.
Publishing requires the Apple credentials. The `afterSign` hook owns `.app`
notarization (so electron-builder's second notarization path is disabled), and
`artifactBuildCompleted` (`scripts/notarize-dmg.mjs`) signs the outer `.dmg`
with `--timestamp`, notarizes and staples it, verifies `codesign`, `stapler`,
and `spctl -t open --context context:primary-signature`, and refreshes
`.dmg.blockmap` and feed hashes from the stapled bytes. The publish gate and
macOS smoke verify both the outer `.dmg` and the contained `.app`.
Recording the build refuses an update ZIP of 1 GiB (1,073,741,824 bytes) or
more: Squirrel.Mac before Electron 44.7, which v0.22.0 ships, reads the whole ZIP
into memory and crashes downloading one that size