Skip to content

The agent that grows with you

refactor(desktop): move --setup-tcc-identity into hermes_cli/main_desktop_tcc.py

Tekniumf9769bbe4b29
diff --git a/hermes_cli/main_desktop.py b/hermes_cli/main_desktop.py
index c66f0b5f541..d0be3038de9 100644
--- a/hermes_cli/main_desktop.py
+++ b/hermes_cli/main_desktop.py
@@ -1,4 +1,4 @@
-"""Desktop (Electron) app: build/stamp, stage-and-swap pack, exe integrity gate, macOS signing/TCC, Linux sandbox, launch (hermes gui/desktop).
+"""Desktop (Electron) app: build/stamp, stage-and-swap pack, exe integrity gate, macOS signing, Linux sandbox, launch (hermes gui/desktop).
Split out of ``hermes_cli/main.py``. Names that still live in main (``PROJECT_ROOT``, ...)
are imported lazily inside the functions that use them (avoids an import cycle).
@@ -17,7 +17,6 @@ import shutil
import stat
import subprocess
import sys
-import tempfile
import time as _time_mod
from pathlib import Path
@@ -887,161 +886,6 @@ def _desktop_macos_relaunchable_fixup(
return _macos_legacy_adhoc_resign(codesign, app)
-def _macos_codesigning_identity_valid(security: str, identity: str) -> bool:
- """True when `identity` is among VALID (``-v``) code-signing identities — the plain listing also
- shows untrusted certs codesign refuses. Idempotency probe + postcondition. Never raises."""
- try:
- result = subprocess.run(
- [security, "find-identity", "-v", "-p", "codesigning"], capture_output=True, text=True, encoding="utf-8", errors="replace", check=False,
- )
- except Exception:
- return False
-
- return f'"{identity}"' in (result.stdout or "")
-
-
-def _macos_create_signing_identity(
- openssl: str, security: str, codesign: str, keychain: str, identity: str) -> bool:
- """Create a self-signed code-signing cert (10 years), import it with codesign access, trust it for codeSign."""
- tmp_dir = Path(tempfile.mkdtemp(prefix="hermes-tcc-"))
- try:
- key = tmp_dir / "sign.key"
- crt = tmp_dir / "sign.crt"
- p12 = tmp_dir / "sign.p12"
- subprocess.run(
- [
- openssl, "req", "-x509", "-newkey", "rsa:2048",
- "-keyout", str(key), "-out", str(crt),
- "-days", "3650", "-nodes",
- "-subj", f"/CN={identity}",
- "-addext", "basicConstraints=critical,CA:TRUE",
- "-addext", "keyUsage=critical,digitalSignature,keyCertSign",
- "-addext", "extendedKeyUsage=codeSigning",
- ],
- capture_output=True, check=True)
-
- # OpenSSL 3 defaults to AES/SHA-2 PKCS#12 that `security import` rejects
- # with "MAC verification failed". `-legacy` restores the accepted
- # RC2/SHA-1 format but only exists on OpenSSL 3 — so try plain first and
- # fall back to `-legacy` when the IMPORT fails with that signature.
- # (Verified E2E on macOS 26.3.1 / OpenSSL 3.6.3 by @ctaylor86 on PR #77189.)
- def _export_p12(extra_args: list) -> None:
- subprocess.run(
- [
- openssl, "pkcs12", "-export", *extra_args,
- "-inkey", str(key), "-in", str(crt),
- "-out", str(p12), "-passout", "pass:hermeslocal",
- ],
- capture_output=True, check=True)
-
- def _import_p12():
- return subprocess.run(
- [
- security, "import", str(p12), "-k", keychain,
- "-P", "hermeslocal",
- "-T", codesign, "-T", "/usr/bin/codesign_allocate",
- ],
- capture_output=True, text=True, encoding="utf-8", errors="replace", check=False)
-
- _export_p12([])
- imported = _import_p12()
- if imported.returncode != 0 and "MAC verification failed" in (imported.stderr or ""):
- # older OpenSSL without -legacy: keep the original failure
- with contextlib.suppress(subprocess.CalledProcessError):
- _export_p12(["-legacy"])
- imported = _import_p12()
- if imported.returncode != 0:
- print(f" (could not import signing identity into keychain: {imported.stderr.strip()})")
- return False
-
- # Without explicit trust for the codeSign policy `find-identity -v`
- # reports 0 valid identities. This writes user trust settings, so macOS
- # may prompt for the login password ONCE — the one-time cost this
- # command exists to front-load.
- trusted = subprocess.run(
- [security, "add-trusted-cert", "-r", "trustRoot", "-p", "codeSign", "-k", keychain, str(crt)],
- capture_output=True, text=True, encoding="utf-8", errors="replace", check=False)
- if trusted.returncode != 0:
- print(
- " (could not trust the certificate for code signing: "
- f"{(trusted.stderr or trusted.stdout).strip()})"
- )
- return False
- print(f" → created, imported, and trusted self-signed identity: {identity!r}")
- return True
- except Exception as exc:
- print(f" (certificate creation failed: {exc})")
- return False
- finally:
- shutil.rmtree(tmp_dir, ignore_errors=True)
-
-
-def _desktop_macos_setup_tcc_identity(identity: str = "Hermes Local Signing") -> bool:
- """``--setup-tcc-identity``: create/import a self-signed code-signing cert, point
- ``desktop.macos_signing_identity`` at it and re-sign the packaged app. TCC grants follow the
- signing identity, so a certificate-anchored one is stable across rebuilds (the yabai/skhd
- mechanism). Idempotent; never raises."""
- from hermes_cli.main import PROJECT_ROOT
- if sys.platform != "darwin":
- print(" (--setup-tcc-identity is macOS-only; skipping)")
- return False
-
- openssl = shutil.which("openssl")
- security = shutil.which("security")
- codesign = shutil.which("codesign")
- if not (openssl and security and codesign):
- print(
- " (--setup-tcc-identity requires openssl, security, and codesign; "
- f"found openssl={bool(openssl)} security={bool(security)} codesign={bool(codesign)})"
- )
- return False
-
- keychain = str(Path.home() / "Library" / "Keychains" / "login.keychain-db")
- # Probe with `-v` (valid identities only) so a previously imported-but-
- # untrusted cert is repaired rather than reported as done.
- if _macos_codesigning_identity_valid(security, identity):
- print(f" → identity {identity!r} already valid in keychain")
- elif not _macos_create_signing_identity(openssl, security, codesign, keychain, identity):
- return False
-
- # Postcondition gate: name-in-output checks pass for invalid identities;
- # only macOS agreeing the identity is usable counts.
- if not _macos_codesigning_identity_valid(security, identity):
- print(
- f" (identity {identity!r} was imported but is not a VALID code-signing identity; "
- "run `security find-identity -v -p codesigning` to inspect, and see the manual "
- "Keychain Access steps in the desktop docs)"
- )
- return False
-
- # config.yaml, not .env — it's not a secret.
- try:
- from hermes_cli.config import set_config_value
- set_config_value("desktop.macos_signing_identity", identity)
- print(f" → set desktop.macos_signing_identity = {identity!r}")
- except Exception as exc:
- print(f" (could not write desktop.macos_signing_identity: {exc})")
- return False
-
- desktop_dir = PROJECT_ROOT / "apps" / "desktop"
- if _desktop_packaged_executable(desktop_dir) is not None:
- try:
- if _desktop_macos_relaunchable_fixup(desktop_dir):
- print(
- " → packaged app re-signed with certificate-anchored identity; "
- "TCC grants persist across rebuilds"
- )
- except Exception as exc:
- print(f" (could not re-sign packaged app: {exc})")
-
- print(
- "\n Note: macOS will re-prompt for permissions ONE final time (the identity "
- "changed). Grant them and they persist from then on. If a permission gets "
- "stuck, reset it with: tccutil reset All com.nousresearch.hermes"
- )
- return True
-
-
def _app_asar_hash(app_path: Path) -> str | None:
"""Return the SHA-256 hex digest of an app bundle's app.asar, or None."""
asar = app_path / "Contents" / "Resources" / "app.asar"
@@ -1826,6 +1670,7 @@ def cmd_gui(args: argparse.Namespace):
# macOS-only one-shot: create a self-signed code-signing identity so TCC
# grants survive rebuilds, then exit without building/launching.
if getattr(args, "setup_tcc_identity", False):
+ from hermes_cli.main_desktop_tcc import _desktop_macos_setup_tcc_identity
identity = getattr(args, "identity", None) or "Hermes Local Signing"
sys.exit(0 if _desktop_macos_setup_tcc_identity(identity) else 1)
diff --git a/hermes_cli/main_desktop_tcc.py b/hermes_cli/main_desktop_tcc.py
new file mode 100644
index 00000000000..20278a3f1f1
--- /dev/null
+++ b/hermes_cli/main_desktop_tcc.py
@@ -0,0 +1,168 @@
+"""``hermes gui --setup-tcc-identity``: a persistent self-signed macOS code-signing identity.
+
+Split out of ``hermes_cli/main_desktop.py``. The facade's build/sign helpers are imported lazily
+inside the function that uses them (the facade late-imports this module from ``cmd_gui``).
+"""
+
+import contextlib
+import shutil
+import subprocess
+import sys
+import tempfile
+from pathlib import Path
+
+
+def _macos_codesigning_identity_valid(security: str, identity: str) -> bool:
+ """True when `identity` is among VALID (``-v``) code-signing identities — the plain listing also
+ shows untrusted certs codesign refuses. Idempotency probe + postcondition. Never raises."""
+ try:
+ result = subprocess.run(
+ [security, "find-identity", "-v", "-p", "codesigning"], capture_output=True, text=True, encoding="utf-8", errors="replace", check=False,
+ )
+ except Exception:
+ return False
+
+ return f'"{identity}"' in (result.stdout or "")
+
+
+def _macos_create_signing_identity(
+ openssl: str, security: str, codesign: str, keychain: str, identity: str) -> bool:
+ """Create a self-signed code-signing cert (10 years), import it with codesign access, trust it for codeSign."""
+ tmp_dir = Path(tempfile.mkdtemp(prefix="hermes-tcc-"))
+ try:
+ key = tmp_dir / "sign.key"
+ crt = tmp_dir / "sign.crt"
+ p12 = tmp_dir / "sign.p12"
+ subprocess.run(
+ [
+ openssl, "req", "-x509", "-newkey", "rsa:2048",
+ "-keyout", str(key), "-out", str(crt),
+ "-days", "3650", "-nodes",
+ "-subj", f"/CN={identity}",
+ "-addext", "basicConstraints=critical,CA:TRUE",
+ "-addext", "keyUsage=critical,digitalSignature,keyCertSign",
+ "-addext", "extendedKeyUsage=codeSigning",
+ ],
+ capture_output=True, check=True)
+
+ # OpenSSL 3 defaults to AES/SHA-2 PKCS#12 that `security import` rejects
+ # with "MAC verification failed". `-legacy` restores the accepted
+ # RC2/SHA-1 format but only exists on OpenSSL 3 — so try plain first and
+ # fall back to `-legacy` when the IMPORT fails with that signature.
+ # (Verified E2E on macOS 26.3.1 / OpenSSL 3.6.3 by @ctaylor86 on PR #77189.)
+ def _export_p12(extra_args: list) -> None:
+ subprocess.run(
+ [
+ openssl, "pkcs12", "-export", *extra_args,
+ "-inkey", str(key), "-in", str(crt),
+ "-out", str(p12), "-passout", "pass:hermeslocal",
+ ],
+ capture_output=True, check=True)
+
+ def _import_p12():
+ return subprocess.run(
+ [
+ security, "import", str(p12), "-k", keychain,
+ "-P", "hermeslocal",
+ "-T", codesign, "-T", "/usr/bin/codesign_allocate",
+ ],
+ capture_output=True, text=True, encoding="utf-8", errors="replace", check=False)
+
+ _export_p12([])
+ imported = _import_p12()
+ if imported.returncode != 0 and "MAC verification failed" in (imported.stderr or ""):
+ # older OpenSSL without -legacy: keep the original failure
+ with contextlib.suppress(subprocess.CalledProcessError):
+ _export_p12(["-legacy"])
+ imported = _import_p12()
+ if imported.returncode != 0:
+ print(f" (could not import signing identity into keychain: {imported.stderr.strip()})")
+ return False
+
+ # Without explicit trust for the codeSign policy `find-identity -v`
+ # reports 0 valid identities. This writes user trust settings, so macOS
+ # may prompt for the login password ONCE — the one-time cost this
+ # command exists to front-load.
+ trusted = subprocess.run(
+ [security, "add-trusted-cert", "-r", "trustRoot", "-p", "codeSign", "-k", keychain, str(crt)],
+ capture_output=True, text=True, encoding="utf-8", errors="replace", check=False)
+ if trusted.returncode != 0:
+ print(
+ " (could not trust the certificate for code signing: "
+ f"{(trusted.stderr or trusted.stdout).strip()})"
+ )
+ return False
+ print(f" → created, imported, and trusted self-signed identity: {identity!r}")
+ return True
+ except Exception as exc:
+ print(f" (certificate creation failed: {exc})")
+ return False
+ finally:
+ shutil.rmtree(tmp_dir, ignore_errors=True)
+
+
+def _desktop_macos_setup_tcc_identity(identity: str = "Hermes Local Signing") -> bool:
+ """``--setup-tcc-identity``: create/import a self-signed code-signing cert, point
+ ``desktop.macos_signing_identity`` at it and re-sign the packaged app. TCC grants follow the
+ signing identity, so a certificate-anchored one is stable across rebuilds (the yabai/skhd
+ mechanism). Idempotent; never raises."""
+ from hermes_cli.main import PROJECT_ROOT
+ from hermes_cli.main_desktop import _desktop_macos_relaunchable_fixup, _desktop_packaged_executable
+ if sys.platform != "darwin":
+ print(" (--setup-tcc-identity is macOS-only; skipping)")
+ return False
+
+ openssl = shutil.which("openssl")
+ security = shutil.which("security")
+ codesign = shutil.which("codesign")
+ if not (openssl and security and codesign):
+ print(
+ " (--setup-tcc-identity requires openssl, security, and codesign; "
+ f"found openssl={bool(openssl)} security={bool(security)} codesign={bool(codesign)})"
+ )
+ return False
+
+ keychain = str(Path.home() / "Library" / "Keychains" / "login.keychain-db")
+ # Probe with `-v` (valid identities only) so a previously imported-but-
+ # untrusted cert is repaired rather than reported as done.
+ if _macos_codesigning_identity_valid(security, identity):
+ print(f" → identity {identity!r} already valid in keychain")
+ elif not _macos_create_signing_identity(openssl, security, codesign, keychain, identity):
+ return False
+
+ # Postcondition gate: name-in-output checks pass for invalid identities;
+ # only macOS agreeing the identity is usable counts.
+ if not _macos_codesigning_identity_valid(security, identity):
+ print(
+ f" (identity {identity!r} was imported but is not a VALID code-signing identity; "
+ "run `security find-identity -v -p codesigning` to inspect, and see the manual "
+ "Keychain Access steps in the desktop docs)"
+ )
+ return False
+
+ # config.yaml, not .env — it's not a secret.
+ try:
+ from hermes_cli.config import set_config_value
+ set_config_value("desktop.macos_signing_identity", identity)
+ print(f" → set desktop.macos_signing_identity = {identity!r}")
+ except Exception as exc:
+ print(f" (could not write desktop.macos_signing_identity: {exc})")
+ return False
+
+ desktop_dir = PROJECT_ROOT / "apps" / "desktop"
+ if _desktop_packaged_executable(desktop_dir) is not None:
+ try:
+ if _desktop_macos_relaunchable_fixup(desktop_dir):
+ print(
+ " → packaged app re-signed with certificate-anchored identity; "
+ "TCC grants persist across rebuilds"
+ )
+ except Exception as exc:
+ print(f" (could not re-sign packaged app: {exc})")
+
+ print(
+ "\n Note: macOS will re-prompt for permissions ONE final time (the identity "
+ "changed). Grant them and they persist from then on. If a permission gets "
+ "stuck, reset it with: tccutil reset All com.nousresearch.hermes"
+ )
+ return True
diff --git a/tests/fixtures/resolution_allowlist.json b/tests/fixtures/resolution_allowlist.json
index ff94cfcb300..9c16870afef 100644
--- a/tests/fixtures/resolution_allowlist.json
+++ b/tests/fixtures/resolution_allowlist.json
@@ -280,7 +280,7 @@
"kind": "bare_which"
},
{
- "path": "hermes_cli/main_desktop.py",
+ "path": "hermes_cli/main_desktop_tcc.py",
"symbol": "_desktop_macos_setup_tcc_identity",
"kind": "bare_which"
},
diff --git a/tests/hermes_cli/test_gui_command.py b/tests/hermes_cli/test_gui_command.py
index 1548024d849..a6ed849c9c6 100644
--- a/tests/hermes_cli/test_gui_command.py
+++ b/tests/hermes_cli/test_gui_command.py
@@ -15,6 +15,7 @@ import pytest
from hermes_cli import main as cli_main
from hermes_cli import main_desktop
+from hermes_cli import main_desktop_tcc
from hermes_cli import main_install_repair
from hermes_cli import main_web_build
@@ -485,7 +486,7 @@ def test_setup_tcc_identity_creates_cert_imports_trusts_and_configures(tmp_path,
# Avoid writing the real user config.
monkeypatch.setattr("hermes_cli.config.set_config_value", lambda key, value: None)
- assert main_desktop._desktop_macos_setup_tcc_identity(identity) is True
+ assert main_desktop_tcc._desktop_macos_setup_tcc_identity(identity) is True
# openssl cert generation + pkcs12 export + security import + trust all ran.
assert any(c[0] == "/usr/bin/openssl" and "req" in c for c in calls)
@@ -540,7 +541,7 @@ def test_setup_tcc_identity_retries_pkcs12_with_legacy_on_mac_verification_failu
monkeypatch.setattr(main_desktop, "_desktop_macos_relaunchable_fixup", lambda d: True)
monkeypatch.setattr("hermes_cli.config.set_config_value", lambda key, value: None)
- assert main_desktop._desktop_macos_setup_tcc_identity(identity) is True
+ assert main_desktop_tcc._desktop_macos_setup_tcc_identity(identity) is True
# Two pkcs12 exports (plain then -legacy) and two import attempts.
pkcs12_calls = [c for c in calls if c[0] == "/usr/bin/openssl" and "pkcs12" in c]
@@ -569,7 +570,7 @@ def test_setup_tcc_identity_fails_when_trust_step_fails(tmp_path, monkeypatch, c
monkeypatch.setattr(cli_main.subprocess, "run", fake_run)
- assert main_desktop._desktop_macos_setup_tcc_identity("Hermes Local Signing") is False
+ assert main_desktop_tcc._desktop_macos_setup_tcc_identity("Hermes Local Signing") is False
@pytest.mark.platforms("macos")
@@ -591,7 +592,7 @@ def test_setup_tcc_identity_fails_when_identity_never_becomes_valid(tmp_path, mo
monkeypatch.setattr(cli_main.subprocess, "run", fake_run)
- assert main_desktop._desktop_macos_setup_tcc_identity("Hermes Local Signing") is False
+ assert main_desktop_tcc._desktop_macos_setup_tcc_identity("Hermes Local Signing") is False
@pytest.mark.platforms("macos")
@@ -617,7 +618,7 @@ def test_setup_tcc_identity_skips_generation_when_already_valid(tmp_path, monkey
monkeypatch.setattr(main_desktop, "_desktop_macos_relaunchable_fixup", lambda d: True)
monkeypatch.setattr("hermes_cli.config.set_config_value", lambda key, value: None)
- assert main_desktop._desktop_macos_setup_tcc_identity("Hermes Local Signing") is True
+ assert main_desktop_tcc._desktop_macos_setup_tcc_identity("Hermes Local Signing") is True
# No openssl generation, no security import — only find-identity + config.
assert not any(c[0] == "/usr/bin/openssl" for c in calls)
@@ -657,7 +658,7 @@ def test_setup_tcc_identity_untrusted_existing_cert_is_repaired(tmp_path, monkey
monkeypatch.setattr(main_desktop, "_desktop_macos_relaunchable_fixup", lambda d: True)
monkeypatch.setattr("hermes_cli.config.set_config_value", lambda key, value: None)
- assert main_desktop._desktop_macos_setup_tcc_identity("Hermes Local Signing") is True
+ assert main_desktop_tcc._desktop_macos_setup_tcc_identity("Hermes Local Signing") is True
assert any(c[0] == "/usr/bin/security" and c[1] == "add-trusted-cert" for c in calls)
@@ -670,7 +671,7 @@ def test_cmd_gui_setup_tcc_identity_exits_before_build(tmp_path, monkeypatch):
monkeypatch.setattr(cli_main, "PROJECT_ROOT", root)
_make_packaged_executable(root, monkeypatch)
- with patch("hermes_cli.main_desktop._desktop_macos_setup_tcc_identity", return_value=True) as mock_setup, \
+ with patch("hermes_cli.main_desktop_tcc._desktop_macos_setup_tcc_identity", return_value=True) as mock_setup, \
patch("hermes_cli.source_build.prepare_source_dependencies") as mock_install, \
pytest.raises(SystemExit) as exc:
cli_main.cmd_gui(_ns(setup_tcc_identity=True, identity="Hermes Local Signing"))