The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(desktop): sign Mach-O members inside payload wheel zips before notarization
ethie3bbb10c250bb
diff --git a/apps/desktop/scripts/after-pack.mjs b/apps/desktop/scripts/after-pack.mjsindex d07c4aef920..2036de06a21 100644--- a/apps/desktop/scripts/after-pack.mjs+++ b/apps/desktop/scripts/after-pack.mjs@@ -26,6 +26,7 @@ import { runPython } from '../../../scripts/build/python.mjs'import { batchSignAppTree } from './batch-sign-binaries.mjs'import { rehashPayloadDigests } from './payload-digests.mjs'import { resolveSigningIdentity, signNestedChromium } from './sign-nested-chromium.mjs'+import { signWheelZipMembers } from './sign-wheel-zips.mjs'import { sanitizeTree } from './sanitize-pe-signatures.mjs'import { stampExeIdentity } from './set-exe-identity.mjs'@@ -48,6 +49,14 @@ export default async function afterPack(context) {`[after-pack] repaired ${nested.repaired} framework links; signed ${nested.signed} nested chromium targets` +(identity ? ` as ${identity}` : ' (no Developer ID in the builder keychain)'))+ // uv-cache wheel zips carry Mach-O members the notary validates but+ // electron-osx-sign cannot reach; sign them in place (see module doc).+ const wheels = signWheelZipMembers(payload, { identity, keychain })+ if (wheels.signed > 0) {+ console.log(+ `[after-pack] signed ${wheels.signed} Mach-O members across ${wheels.wheels} payload wheel zips` ++ (identity ? ` as ${identity}` : ' (no Developer ID in the builder keychain)'))+ }// The macOS signer refreshes this again before sealing the outer app.// Unsigned builds end here and still need final-byte facts.rehashPayloadDigests(payload)diff --git a/apps/desktop/scripts/sign-wheel-zips.mjs b/apps/desktop/scripts/sign-wheel-zips.mjsnew file mode 100644index 00000000000..7caa8834010--- /dev/null+++ b/apps/desktop/scripts/sign-wheel-zips.mjs@@ -0,0 +1,117 @@+// sign-wheel-zips.mjs — sign Mach-O members inside payload uv-cache wheel zips.+//+// uv's cache keeps built wheels as ZIPs beside the extracted archive buckets.+// electron-osx-sign signs the extracted trees but cannot reach inside a ZIP;+// Apple's notary extracts every zip and validates each Mach-O, so an+// unsigned member fails the whole submission (err 4000, "not signed with a+// valid Developer ID certificate"). After our round-5 cache work the zips+// are load-bearing for offline per-install venv rebuilds, so we sign the+// members instead of dropping them.+//+// Mechanism (proven on a real macOS 26 host): extract → codesign --timestamp+// --options runtime → repack → extract again → codesign --verify --strict.+// The verify gate is mandatory: with a real Developer ID the signature is+// embedded in the Mach-O and survives plain-zip roundtrips; if a host ever+// degrades to xattr-only signatures, the gate fails the build instead of+// shipping an app the notary will reject anyway.++import { execFileSync } from 'node:child_process'+import fs from 'node:fs'+import os from 'node:os'+import path from 'node:path'+import { isMachO } from './sign-nested-chromium.mjs'++const MACHO_EXTENSIONS = new Set(['.so', '.dylib'])++function listWheelFiles(payload) {+ const cache = path.join(payload, 'uv-cache')+ if (!fs.existsSync(cache)) return []+ const out = []+ const walk = dir => {+ let entries+ try {+ entries = fs.readdirSync(dir, { withFileTypes: true })+ } catch {+ return+ }+ for (const ent of entries) {+ const p = path.join(dir, ent.name)+ if (ent.isDirectory()) walk(p)+ else if (ent.isFile() && p.endsWith('.whl')) out.push(p)+ }+ }+ walk(cache)+ return out+}++function run(exec, command, args, options = {}) {+ return exec(command, args, { stdio: ['ignore', 'pipe', 'pipe'], encoding: 'utf8', ...options })+}++export function signWheelZipMembers(payload, opts = {}) {+ const identity = opts.identity+ const wheels = listWheelFiles(payload)+ if (!identity) return { wheels: wheels.length, signed: 0, failed: 0 }+ const exec = opts.exec ?? execFileSync+ const keychain = opts.keychain || null+ const work = fs.mkdtempSync(path.join(os.tmpdir(), 'wheel-sign-'))+ try {+ let signed = 0+ let failed = 0+ for (const wheel of wheels) {+ const wheelWork = path.join(work, path.basename(wheel).replace(/[^\w.-]/g, '_'))+ fs.mkdirSync(path.join(wheelWork, 'extract'), { recursive: true })+ const extract = path.join(wheelWork, 'extract')+ run(exec, 'unzip', ['-q', '-o', wheel, '-d', extract])+ let wheelTouched = false+ const members = []+ const walk = dir => {+ for (const ent of fs.readdirSync(dir, { withFileTypes: true })) {+ const p = path.join(dir, ent.name)+ if (ent.isDirectory()) { walk(p); continue }+ if (!ent.isFile() || !MACHO_EXTENSIONS.has(path.extname(p))) continue+ members.push(p)+ }+ }+ walk(extract)+ for (const member of members) {+ if (!isMachO(member)) continue+ const args = ['--force', '--sign', identity, '--timestamp', '--options', 'runtime']+ if (keychain) args.push('--keychain', keychain)+ args.push(member)+ run(exec, 'codesign', args)+ signed += 1+ wheelTouched = true+ }+ if (!wheelTouched) {+ fs.rmSync(wheelWork, { recursive: true, force: true })+ continue+ }+ // Repack preserving directory structure; the verify gate below proves+ // the embedded signature survived this host's zip semantics.+ const repacked = path.join(wheelWork, 'repacked.whl')+ run(exec, 'zip', ['-q', '-r', '-X', repacked, '.'], { cwd: extract })+ // Verify from a FRESH extraction: the predicate the notary applies.+ const verify = path.join(wheelWork, 'verify')+ fs.mkdirSync(verify, { recursive: true })+ run(exec, 'unzip', ['-q', '-o', repacked, '-d', verify])+ for (const member of members) {+ const rel = path.relative(extract, member)+ const candidate = path.join(verify, rel)+ try {+ run(exec, 'codesign', ['--verify', '--strict', candidate])+ } catch (error) {+ failed += 1+ throw new Error(+ `sign-wheel-zips: ${path.basename(wheel)}:${rel} lost its signature through the repack ` ++ `(embedded Developer ID signatures must survive a zip roundtrip): ${error.message}`)+ }+ }+ fs.copyFileSync(repacked, wheel)+ fs.rmSync(wheelWork, { recursive: true, force: true })+ }+ return { wheels: wheels.length, signed, failed }+ } finally {+ fs.rmSync(work, { recursive: true, force: true })+ }+}diff --git a/apps/desktop/scripts/sign-wheel-zips.test.mjs b/apps/desktop/scripts/sign-wheel-zips.test.mjsnew file mode 100644index 00000000000..ae098e86807--- /dev/null+++ b/apps/desktop/scripts/sign-wheel-zips.test.mjs@@ -0,0 +1,175 @@+import { describe, expect, it } from 'vitest'+import fs from 'node:fs'+import os from 'node:os'+import path from 'node:path'+import { signWheelZipMembers } from './sign-wheel-zips.mjs'++function crc32(data) {+ const table = new Uint32Array(256)+ for (let i = 0; i < 256; i++) {+ let c = i+ for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1+ table[i] = c >>> 0+ }+ let crc = -1+ for (const byte of data) crc = (crc >>> 8) ^ table[(crc ^ byte) & 0xff]+ return (crc ^ -1) >>> 0+}++function storedZip(members) {+ const chunks = []+ const central = []+ let offset = 0+ for (const [member, data] of Object.entries(members)) {+ const nameBuf = Buffer.from(member)+ const crc = crc32(data)+ const local = Buffer.alloc(30)+ local.writeUInt32LE(0x04034b50, 0)+ local.writeUInt16LE(20, 4)+ local.writeUInt32LE(crc, 14)+ local.writeUInt32LE(data.length, 18)+ local.writeUInt32LE(data.length, 22)+ local.writeUInt16LE(nameBuf.length, 26)+ chunks.push(local, nameBuf, data)+ const entry = Buffer.alloc(46)+ entry.writeUInt32LE(0x02014b50, 0)+ entry.writeUInt16LE(20, 4)+ entry.writeUInt16LE(20, 6)+ entry.writeUInt32LE(crc, 16)+ entry.writeUInt32LE(data.length, 20)+ entry.writeUInt32LE(data.length, 24)+ entry.writeUInt16LE(nameBuf.length, 28)+ entry.writeUInt32LE(offset, 42)+ central.push(entry, nameBuf)+ offset += 30 + nameBuf.length + data.length+ }+ const centralBuf = Buffer.concat(central)+ const end = Buffer.alloc(22)+ end.writeUInt32LE(0x06054b50, 0)+ end.writeUInt16LE(Object.keys(members).length, 10)+ end.writeUInt32LE(centralBuf.length, 12)+ end.writeUInt32LE(offset, 16)+ return Buffer.concat([...chunks, centralBuf, end])+}++function makeWheel(payload, name, members) {+ const wheelDir = path.join(payload, 'uv-cache', 'wheels-v6', 'pypi', name)+ fs.mkdirSync(wheelDir, { recursive: true })+ const wheelPath = path.join(wheelDir, `${name}-1.0.0-py3-none-any.whl`)+ fs.writeFileSync(wheelPath, storedZip(members))+ return wheelPath+}++describe('signWheelZipMembers', () => {+ it('is a no-op without an identity', () => {+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'wz-'))+ try {+ const payload = path.join(root, 'agent-payload')+ makeWheel(payload, 'pure-pkg', { 'pure/pkg.py': Buffer.from('x = 1') })+ expect(signWheelZipMembers(payload, { identity: null }))+ .toEqual({ wheels: 1, signed: 0, failed: 0 })+ } finally {+ fs.rmSync(root, { recursive: true, force: true })+ }+ })++ it('reports zero for payloads without a uv-cache', () => {+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'wz-'))+ try {+ expect(signWheelZipMembers(path.join(root, 'empty'), { identity: 'ABC' }))+ .toEqual({ wheels: 0, signed: 0, failed: 0 })+ } finally {+ fs.rmSync(root, { recursive: true, force: true })+ }+ })+})++describe('signWheelZipMembers machinery', () => {+ it('walks Mach-O members and gates on verify', () => {+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'wz-'))+ try {+ const payload = path.join(root, 'agent-payload')+ // Mach-O magic bytes: 0xfeedfacf (64-bit little endian swapped)+ const macho = Buffer.from([0xcf, 0xfa, 0xed, 0xfe, 0, 1, 2, 3])+ makeWheel(payload, 'native-pkg', {+ 'native/_speedups.so': macho,+ 'native/data.json': Buffer.from('{}'),+ })+ const calls = []+ // The stub simulates unzip/zip/codesign on the stored-zip format the+ // fixture writes: unzip materializes members, codesign mutates the last+ // byte (a fake embedded signature), zip repacks from disk.+ const membersOf = wheelPath => {+ const buf = fs.readFileSync(wheelPath)+ const out = {}+ let off = 0+ while (buf.readUInt32LE(off) === 0x04034b50) {+ const nameLen = buf.readUInt16LE(off + 26)+ const size = buf.readUInt32LE(off + 18)+ const name = buf.toString('utf8', off + 30, off + 30 + nameLen)+ out[name] = buf.subarray(off + 30 + nameLen, off + 30 + nameLen + size)+ off += 30 + nameLen + size+ }+ return out+ }+ let original = null+ const fakeExec = (command, args, options = {}) => {+ calls.push([command, ...args])+ if (command === 'unzip') {+ const wheel = args.find(a => a.endsWith('.whl'))+ original = membersOf(wheel)+ const dest = args[args.indexOf('-d') + 1]+ for (const [name, data] of Object.entries(original)) {+ fs.mkdirSync(path.join(dest, path.dirname(name)), { recursive: true })+ fs.writeFileSync(path.join(dest, name), data)+ }+ } else if (command === 'codesign') {+ const target = args[args.length - 1]+ const buf = fs.readFileSync(target)+ buf[buf.length - 1] ^= 0xff+ fs.writeFileSync(target, buf)+ } else if (command === 'zip') {+ const out = args[args.indexOf('-r') + 2]+ const src = options.cwd+ const members = {}+ const walk = dir => {+ for (const ent of fs.readdirSync(dir, { withFileTypes: true })) {+ const p = path.join(dir, ent.name)+ if (ent.isDirectory()) walk(p)+ else members[path.relative(src, p)] = fs.readFileSync(p)+ }+ }+ walk(src)+ fs.writeFileSync(out, storedZip(members))+ }+ }+ const result = signWheelZipMembers(payload, { identity: 'DEVID', exec: fakeExec })+ expect(result.signed).toBe(1)+ const commands = calls.map(c => c[0])+ expect(commands).toContain('unzip')+ expect(commands).toContain('codesign')+ expect(commands).toContain('zip')+ // The verify gate ran codesign --verify against the repacked extraction.+ expect(calls.filter(c => c[0] === 'codesign' && c.includes('--verify')).length).toBe(1)+ } finally {+ fs.rmSync(root, { recursive: true, force: true })+ }+ })++ it('skips wheels without Mach-O members without touching them', () => {+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'wz-'))+ try {+ const payload = path.join(root, 'agent-payload')+ const wheelPath = makeWheel(payload, 'pure-pkg', { 'pure/pkg.py': Buffer.from('x = 1') })+ const before = fs.readFileSync(wheelPath)+ const calls = []+ const result = signWheelZipMembers(payload, { identity: 'DEVID', exec: (...a) => calls.push(a) })+ expect(result.signed).toBe(0)+ expect(fs.readFileSync(wheelPath).equals(before)).toBe(true)+ // Only the probe unzip runs; no codesign, no repack.+ expect(calls.filter(c => c[0] !== 'unzip').length).toBe(0)+ } finally {+ fs.rmSync(root, { recursive: true, force: true })+ }+ })+})