Skip to content

The agent that grows with you

fix(notarize): retry ticket lookup after confirmed acceptance

ethernet0de874c423b1
diff --git a/apps/desktop/scripts/notarize.mjs b/apps/desktop/scripts/notarize.mjs
index 49294469e55..a7b72f4c9cc 100644
--- a/apps/desktop/scripts/notarize.mjs
+++ b/apps/desktop/scripts/notarize.mjs
@@ -2,15 +2,17 @@ import fs from 'node:fs'
import os from 'node:os'
import path from 'node:path'
import { execFile } from 'node:child_process'
+import { setTimeout } from 'node:timers/promises'
-function run(command, args) {
+export function runCommand(command, args, options = {}) {
return new Promise((resolve, reject) => {
- execFile(command, args, (error, stdout, stderr) => {
+ execFile(command, args, options, (error, stdout, stderr) => {
if (error) {
reject(
- new Error(
- `${command} ${args.join(' ')} failed: ${stderr?.trim() || stdout?.trim() || error.message}`
- )
+ Object.assign(new Error(
+ `${command} ${args.join(' ')} failed: ${stderr?.trim() || stdout?.trim() || error.message}`,
+ { cause: error }
+ ), { code: error.code, stdout, stderr })
)
return
}
@@ -49,7 +51,60 @@ function resolveApiKeyPath(rawValue) {
}
}
-export default async function notarize(context) {
+async function submitAndStaple(zipPath, appPath, auth, { run, sleep, log }) {
+ log(`[notarize] submitting ${zipPath}. Waiting for Apple's decision.`)
+ let result
+ let submitError
+ try {
+ result = await run('xcrun', ['notarytool', 'submit', zipPath, ...auth, '--wait', '--output-format', 'json'])
+ } catch (error) {
+ // A rejected submission can still return a JSON result and a log ID.
+ result = error
+ submitError = error
+ }
+ let submission
+ try {
+ submission = JSON.parse(result.stdout)
+ } catch {
+ throw submitError ?? new Error(`Invalid notarytool response: ${result.stdout}`)
+ }
+ const { id, status } = submission ?? {}
+ if (typeof id !== 'string' || !id || typeof status !== 'string') {
+ throw submitError ?? new Error(`Incomplete notarytool response: ${result.stdout}`)
+ }
+ log(`[notarize] submission ${id}: ${status}`)
+ if (submitError || status !== 'Accepted') {
+ let diagnostics
+ try {
+ const result = await run('xcrun', ['notarytool', 'log', id, ...auth], { timeout: 120000 })
+ diagnostics = result.stdout
+ } catch (error) {
+ diagnostics = `Could not retrieve Apple's diagnostic log: ${error.message}`
+ }
+ throw new Error(`Notarization ${id}: ${status}\n${diagnostics}`, { cause: submitError })
+ }
+
+ // Accepted tickets can take time to reach Apple's CloudKit lookup service.
+ const delays = [15000, 30000, 60000, 120000, 120000]
+ for (let attempt = 0; ; attempt++) {
+ try {
+ log(`[notarize] stapling attempt ${attempt + 1}/${delays.length + 1}`)
+ await run('xcrun', ['stapler', 'staple', '-v', appPath], { timeout: 120000 })
+ log(`[notarize] ticket stapled for submission ${id}`)
+ return
+ } catch (error) {
+ const output = `${error.stdout ?? ''}\n${error.stderr ?? ''}\n${error.message}`
+ const missingTicket = error.code === 65 && /CloudKit query[^\n]*Record not found/i.test(output)
+ if (!missingTicket || attempt === delays.length) throw error
+ log(`[notarize] accepted ticket not available. Retrying in ${delays[attempt] / 1000}s.`)
+ await sleep(delays[attempt])
+ }
+ }
+}
+
+export default async function notarize(context, {
+ run = runCommand, env = process.env, sleep = setTimeout, log = console.log
+} = {}) {
const { electronPlatformName, appOutDir, packager } = context
if (electronPlatformName !== 'darwin') return
@@ -59,36 +114,30 @@ export default async function notarize(context) {
throw new Error(`Cannot notarize missing app bundle: ${appPath}`)
}
- const profile = String(process.env.APPLE_NOTARY_PROFILE || '').trim()
+ const profile = String(env.APPLE_NOTARY_PROFILE || '').trim()
+ let auth
+ let cleanup = () => {}
if (profile) {
- const zipPath = path.join(appOutDir, `${appName}.zip`)
- await run('ditto', ['-c', '-k', '--sequesterRsrc', '--keepParent', appPath, zipPath])
- await run('xcrun', ['notarytool', 'submit', zipPath, '--keychain-profile', profile, '--wait'])
- await run('xcrun', ['stapler', 'staple', '-v', appPath])
- try {
- fs.rmSync(zipPath, { force: true })
- } catch {
- // Best-effort cleanup.
+ 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
}
- return
- }
-
- const keyId = String(process.env.APPLE_API_KEY_ID || '').trim()
- const issuer = String(process.env.APPLE_API_ISSUER || '').trim()
- const rawApiKey = process.env.APPLE_API_KEY
- if (!rawApiKey || !keyId || !issuer) {
- console.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 { keyPath, cleanup } = resolveApiKeyPath(rawApiKey)
const zipPath = path.join(appOutDir, `${appName}.zip`)
try {
await run('ditto', ['-c', '-k', '--sequesterRsrc', '--keepParent', appPath, zipPath])
- await run('xcrun', ['notarytool', 'submit', zipPath, '--key', keyPath, '--key-id', keyId, '--issuer', issuer, '--wait'])
- await run('xcrun', ['stapler', 'staple', '-v', appPath])
+ await submitAndStaple(zipPath, appPath, auth, { run, sleep, log })
} finally {
try {
fs.rmSync(zipPath, { force: true })
diff --git a/tests-js/notarize.test.mjs b/tests-js/notarize.test.mjs
new file mode 100644
index 00000000000..ca2df9b279c
--- /dev/null
+++ b/tests-js/notarize.test.mjs
@@ -0,0 +1,109 @@
+import { mkdtempSync, mkdirSync, existsSync, rmSync, writeFileSync } from 'node:fs'
+import os from 'node:os'
+import path from 'node:path'
+import { expect, test, vi } from 'vitest'
+import notarize, { runCommand } from '../apps/desktop/scripts/notarize.mjs'
+
+const submissionId = '00000000-0000-4000-8000-000000000001'
+const missingTicket = () => Object.assign(new Error('CloudKit query for Hermes.app failed due to "Record not found".\nThe staple and validate action failed! Error 65.'), { code: 65 })
+
+function fixture() {
+ const root = mkdtempSync(path.join(os.tmpdir(), 'hermes-notary-test-'))
+ mkdirSync(path.join(root, 'Hermes.app'))
+ const key = path.join(root, 'api-key.p8')
+ writeFileSync(key, 'test credential path only')
+ return {
+ root,
+ context: { electronPlatformName: 'darwin', appOutDir: root, packager: { appInfo: { productFilename: 'Hermes' } } },
+ environments: [
+ { APPLE_NOTARY_PROFILE: 'test-profile' },
+ { APPLE_API_KEY: key, APPLE_API_KEY_ID: 'test-key', APPLE_API_ISSUER: 'test-issuer' }
+ ],
+ cleanup: () => rmSync(root, { recursive: true, force: true })
+ }
+}
+
+test('accepted submissions retry only ticket propagation, without resubmitting or rebuilding', async () => {
+ const f = fixture()
+ try {
+ for (const env of f.environments) {
+ const calls = []
+ let attempts = 0
+ const run = vi.fn(async (command, args) => {
+ calls.push([command, ...args])
+ if (command === 'ditto') writeFileSync(args.at(-1), 'archive fixture')
+ if (args[0] === 'notarytool') return { stdout: JSON.stringify({ id: submissionId, status: 'Accepted' }) }
+ if (args[0] === 'stapler' && ++attempts <= 2) {
+ // Exercise exit-code and output capture with a real child process.
+ return runCommand(process.execPath, ['-e',
+ 'process.stdout.write(process.argv[1]); process.exitCode = 65', missingTicket().message])
+ }
+ return { stdout: '', stderr: '' }
+ })
+ const sleep = vi.fn(async () => {})
+ const log = vi.fn()
+ await notarize(f.context, { run, sleep, log, env })
+ expect(calls.filter(c => c[0] === 'ditto')).toHaveLength(1)
+ const submissions = calls.filter(c => c[1] === 'notarytool' && c[2] === 'submit')
+ expect(submissions).toHaveLength(1)
+ expect(submissions[0]).toEqual(expect.arrayContaining(['--wait', '--output-format', 'json']))
+ expect(submissions[0]).toEqual(expect.arrayContaining(env.APPLE_NOTARY_PROFILE
+ ? ['--keychain-profile', env.APPLE_NOTARY_PROFILE]
+ : ['--key', env.APPLE_API_KEY, '--key-id', env.APPLE_API_KEY_ID, '--issuer', env.APPLE_API_ISSUER]))
+ expect(attempts).toBe(3)
+ expect(sleep.mock.calls.map(([ms]) => ms)).toEqual([15000, 30000])
+ expect(log).toHaveBeenCalledWith(expect.stringContaining(`${submissionId}: Accepted`))
+ expect(existsSync(path.join(f.root, 'Hermes.zip'))).toBe(false)
+ }
+ } finally {
+ f.cleanup()
+ }
+})
+
+test('rejections, unknown failures and exhausted propagation retries remain build failures', async () => {
+ const f = fixture()
+ try {
+ for (const scenario of ['invalid-zero', 'invalid-nonzero', 'malformed', 'auth', 'permanent-staple', 'exhausted']) {
+ const calls = []
+ const run = vi.fn(async (command, args) => {
+ calls.push([command, ...args])
+ if (command === 'ditto') writeFileSync(args.at(-1), 'archive fixture')
+ if (args[0] === 'notarytool' && args[1] === 'log') return { stdout: '{"issues":[{"message":"signature rejected"}]}' }
+ if (args[0] === 'notarytool') {
+ if (scenario === 'auth') throw new Error('authentication failed')
+ if (scenario === 'malformed') return { stdout: 'not JSON' }
+ const stdout = JSON.stringify({ id: submissionId, status: scenario.startsWith('invalid') ? 'Invalid' : 'Accepted' })
+ if (scenario === 'invalid-nonzero') throw Object.assign(new Error('submit failed'), { code: 1, stdout })
+ return { stdout }
+ }
+ if (args[0] === 'stapler') {
+ if (scenario === 'permanent-staple') throw Object.assign(new Error('invalid bundle format'), { code: 65 })
+ throw missingTicket()
+ }
+ return { stdout: '', stderr: '' }
+ })
+ const sleep = vi.fn(async () => {})
+ const failure = await notarize(f.context, { run, sleep, log: vi.fn(), env: f.environments[0] }).catch(e => e)
+ expect(failure).toBeInstanceOf(Error)
+ expect(calls.filter(c => c[2] === 'submit')).toHaveLength(1)
+ const staples = calls.filter(c => c[1] === 'stapler')
+ if (scenario.startsWith('invalid')) {
+ expect(failure.message).toContain('Invalid')
+ expect(failure.message).toContain('signature rejected')
+ expect(calls.filter(c => c[2] === 'log')).toHaveLength(1)
+ expect(staples).toHaveLength(0)
+ } else if (scenario === 'exhausted') {
+ expect(failure.message).toContain('Record not found')
+ expect(staples.length).toBe(sleep.mock.calls.length + 1)
+ expect(staples.length).toBeGreaterThan(1)
+ expect(staples.length).toBeLessThanOrEqual(6)
+ } else {
+ expect(staples).toHaveLength(scenario === 'permanent-staple' ? 1 : 0)
+ }
+ if (scenario !== 'exhausted') expect(sleep).not.toHaveBeenCalled()
+ expect(existsSync(path.join(f.root, 'Hermes.zip'))).toBe(false)
+ }
+ } finally {
+ f.cleanup()
+ }
+})