main_desktop_tcc.py 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168
  1. """``hermes gui --setup-tcc-identity``: a persistent self-signed macOS code-signing identity.
  2. Split out of ``hermes_cli/main_desktop.py``. The facade's build/sign helpers are imported lazily
  3. inside the function that uses them (the facade late-imports this module from ``cmd_gui``).
  4. """
  5. import contextlib
  6. import shutil
  7. import subprocess
  8. import sys
  9. import tempfile
  10. from pathlib import Path
  11. def _macos_codesigning_identity_valid(security: str, identity: str) -> bool:
  12. """True when `identity` is among VALID (``-v``) code-signing identities — the plain listing also
  13. shows untrusted certs codesign refuses. Idempotency probe + postcondition. Never raises."""
  14. try:
  15. result = subprocess.run(
  16. [security, "find-identity", "-v", "-p", "codesigning"], capture_output=True, text=True, encoding="utf-8", errors="replace", check=False,
  17. )
  18. except Exception:
  19. return False
  20. return f'"{identity}"' in (result.stdout or "")
  21. def _macos_create_signing_identity(
  22. openssl: str, security: str, codesign: str, keychain: str, identity: str) -> bool:
  23. """Create a self-signed code-signing cert (10 years), import it with codesign access, trust it for codeSign."""
  24. tmp_dir = Path(tempfile.mkdtemp(prefix="hermes-tcc-"))
  25. try:
  26. key = tmp_dir / "sign.key"
  27. crt = tmp_dir / "sign.crt"
  28. p12 = tmp_dir / "sign.p12"
  29. subprocess.run(
  30. [
  31. openssl, "req", "-x509", "-newkey", "rsa:2048",
  32. "-keyout", str(key), "-out", str(crt),
  33. "-days", "3650", "-nodes",
  34. "-subj", f"/CN={identity}",
  35. "-addext", "basicConstraints=critical,CA:TRUE",
  36. "-addext", "keyUsage=critical,digitalSignature,keyCertSign",
  37. "-addext", "extendedKeyUsage=codeSigning",
  38. ],
  39. capture_output=True, check=True)
  40. # OpenSSL 3 defaults to AES/SHA-2 PKCS#12 that `security import` rejects
  41. # with "MAC verification failed". `-legacy` restores the accepted
  42. # RC2/SHA-1 format but only exists on OpenSSL 3 — so try plain first and
  43. # fall back to `-legacy` when the IMPORT fails with that signature.
  44. # (Verified E2E on macOS 26.3.1 / OpenSSL 3.6.3 by @ctaylor86 on PR #77189.)
  45. def _export_p12(extra_args: list) -> None:
  46. subprocess.run(
  47. [
  48. openssl, "pkcs12", "-export", *extra_args,
  49. "-inkey", str(key), "-in", str(crt),
  50. "-out", str(p12), "-passout", "pass:hermeslocal",
  51. ],
  52. capture_output=True, check=True)
  53. def _import_p12():
  54. return subprocess.run(
  55. [
  56. security, "import", str(p12), "-k", keychain,
  57. "-P", "hermeslocal",
  58. "-T", codesign, "-T", "/usr/bin/codesign_allocate",
  59. ],
  60. capture_output=True, text=True, encoding="utf-8", errors="replace", check=False)
  61. _export_p12([])
  62. imported = _import_p12()
  63. if imported.returncode != 0 and "MAC verification failed" in (imported.stderr or ""):
  64. # older OpenSSL without -legacy: keep the original failure
  65. with contextlib.suppress(subprocess.CalledProcessError):
  66. _export_p12(["-legacy"])
  67. imported = _import_p12()
  68. if imported.returncode != 0:
  69. print(f" (could not import signing identity into keychain: {imported.stderr.strip()})")
  70. return False
  71. # Without explicit trust for the codeSign policy `find-identity -v`
  72. # reports 0 valid identities. This writes user trust settings, so macOS
  73. # may prompt for the login password ONCE — the one-time cost this
  74. # command exists to front-load.
  75. trusted = subprocess.run(
  76. [security, "add-trusted-cert", "-r", "trustRoot", "-p", "codeSign", "-k", keychain, str(crt)],
  77. capture_output=True, text=True, encoding="utf-8", errors="replace", check=False)
  78. if trusted.returncode != 0:
  79. print(
  80. " (could not trust the certificate for code signing: "
  81. f"{(trusted.stderr or trusted.stdout).strip()})"
  82. )
  83. return False
  84. print(f" → created, imported, and trusted self-signed identity: {identity!r}")
  85. return True
  86. except Exception as exc:
  87. print(f" (certificate creation failed: {exc})")
  88. return False
  89. finally:
  90. shutil.rmtree(tmp_dir, ignore_errors=True)
  91. def _desktop_macos_setup_tcc_identity(identity: str = "Hermes Local Signing") -> bool:
  92. """``--setup-tcc-identity``: create/import a self-signed code-signing cert, point
  93. ``desktop.macos_signing_identity`` at it and re-sign the packaged app. TCC grants follow the
  94. signing identity, so a certificate-anchored one is stable across rebuilds (the yabai/skhd
  95. mechanism). Idempotent; never raises."""
  96. from hermes_cli.main import PROJECT_ROOT
  97. from hermes_cli.main_desktop import _desktop_macos_relaunchable_fixup, _desktop_packaged_executable
  98. if sys.platform != "darwin":
  99. print(" (--setup-tcc-identity is macOS-only; skipping)")
  100. return False
  101. openssl = shutil.which("openssl")
  102. security = shutil.which("security")
  103. codesign = shutil.which("codesign")
  104. if not (openssl and security and codesign):
  105. print(
  106. " (--setup-tcc-identity requires openssl, security, and codesign; "
  107. f"found openssl={bool(openssl)} security={bool(security)} codesign={bool(codesign)})"
  108. )
  109. return False
  110. keychain = str(Path.home() / "Library" / "Keychains" / "login.keychain-db")
  111. # Probe with `-v` (valid identities only) so a previously imported-but-
  112. # untrusted cert is repaired rather than reported as done.
  113. if _macos_codesigning_identity_valid(security, identity):
  114. print(f" → identity {identity!r} already valid in keychain")
  115. elif not _macos_create_signing_identity(openssl, security, codesign, keychain, identity):
  116. return False
  117. # Postcondition gate: name-in-output checks pass for invalid identities;
  118. # only macOS agreeing the identity is usable counts.
  119. if not _macos_codesigning_identity_valid(security, identity):
  120. print(
  121. f" (identity {identity!r} was imported but is not a VALID code-signing identity; "
  122. "run `security find-identity -v -p codesigning` to inspect, and see the manual "
  123. "Keychain Access steps in the desktop docs)"
  124. )
  125. return False
  126. # config.yaml, not .env — it's not a secret.
  127. try:
  128. from hermes_cli.config import set_config_value
  129. set_config_value("desktop.macos_signing_identity", identity)
  130. print(f" → set desktop.macos_signing_identity = {identity!r}")
  131. except Exception as exc:
  132. print(f" (could not write desktop.macos_signing_identity: {exc})")
  133. return False
  134. desktop_dir = PROJECT_ROOT / "apps" / "desktop"
  135. if _desktop_packaged_executable(desktop_dir) is not None:
  136. try:
  137. if _desktop_macos_relaunchable_fixup(desktop_dir):
  138. print(
  139. " → packaged app re-signed with certificate-anchored identity; "
  140. "TCC grants persist across rebuilds"
  141. )
  142. except Exception as exc:
  143. print(f" (could not re-sign packaged app: {exc})")
  144. print(
  145. "\n Note: macOS will re-prompt for permissions ONE final time (the identity "
  146. "changed). Grant them and they persist from then on. If a permission gets "
  147. "stuck, reset it with: tccutil reset All com.nousresearch.hermes"
  148. )
  149. return True