macos-runtime.ts 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. /** Sign final native runtime files before the enclosing Desktop application is signed. */
  2. import { createHash } from 'node:crypto'
  3. import { closeSync, openSync, readSync } from 'node:fs'
  4. import { join } from 'node:path'
  5. import { inventoryDesktopRuntime } from '../src/runtime-tree.ts'
  6. import type { MacOSSigningEnvironment } from './desktop-release-environment.mjs'
  7. import { signMacOSRuntimeCode, verifyMacOSRuntimeCode } from './verify-macos-signature.mjs'
  8. const MACH_O_MAGICS = new Set(['cafebabe', 'cafebabf', 'cefaedfe', 'cffaedfe', 'feedface', 'feedfacf', 'bebafeca', 'bfbafeca'])
  9. function isMachO(path: string): boolean {
  10. const descriptor = openSync(path, 'r')
  11. try {
  12. const header = Buffer.alloc(4)
  13. return readSync(descriptor, header, 0, 4, 0) === 4 && MACH_O_MAGICS.has(header.toString('hex'))
  14. } finally { closeSync(descriptor) }
  15. }
  16. /**
  17. * Sign and verify every materialized Mach-O file, awaiting all signers on failure.
  18. * @param root - Self-contained production runtime without symlinks.
  19. * @param appId - Release application identifier.
  20. * @param expected - Required signing identity.
  21. * @returns Number of signed native files.
  22. */
  23. export async function signMacOSRuntime(root: string, appId: string, expected: MacOSSigningEnvironment): Promise<number> {
  24. const files = inventoryDesktopRuntime(root).map(file => file.path).filter(path => isMachO(join(root, path)))
  25. let next = 0
  26. const workers = Array.from({ length: Math.min(4, files.length) }, async () => {
  27. for (;;) {
  28. const path = files[next++]
  29. if (path === undefined) return
  30. const identifier = `${appId}.runtime.${createHash('sha256').update(path).digest('hex')}`
  31. await signMacOSRuntimeCode(join(root, path), identifier, expected)
  32. verifyMacOSRuntimeCode(join(root, path), expected)
  33. }
  34. })
  35. const results = await Promise.allSettled(workers)
  36. const errors = results.filter(result => result.status === 'rejected').map(result => result.reason as unknown)
  37. if (errors.length > 0) throw new AggregateError(errors, 'desktop runtime: native signing failed')
  38. return files.length
  39. }