The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
feat(desktop): add --setup-tcc-identity to keep macOS TCC grants across rebuilds
CriptoGuseeb391d0b1d5
diff --git a/hermes_cli/main.py b/hermes_cli/main.pyindex ce0691e0333..854cf181858 100644--- a/hermes_cli/main.py+++ b/hermes_cli/main.py@@ -433,6 +433,7 @@ import shleximport shutilimport statimport subprocess+import tempfilefrom pathlib import Pathfrom typing import Optional@@ -7792,6 +7793,127 @@ def _desktop_macos_relaunchable_fixup(return False+def _desktop_macos_setup_tcc_identity(identity: str = "Hermes Local Signing") -> bool:+ """Create/import a self-signed code-signing cert and configure Hermes to use it.++ One-shot setup for ``hermes desktop --setup-tcc-identity``. Creates a+ self-signed "Code Signing" certificate in the login keychain (the same+ artifact the docs describe creating manually via Keychain Access), grants+ ``codesign`` access to it, writes ``desktop.macos_signing_identity`` to+ config.yaml, and re-signs the already-packaged app so the next launch uses+ the certificate-anchored identity.++ Why this matters: macOS TCC grants (Full Disk Access, Accessibility,+ Automation, Files and Folders, microphone) persist against the app's+ code-signing identity, not its path. A plain ad-hoc signature gets a+ cdhash-only Designated Requirement, so every rebuild looks like a new app+ and the user must re-grant everything. A certificate-anchored identity is+ stable across rebuilds — the same mechanism yabai/skhd users rely on.++ Idempotent: re-running after an update finds the existing certificate and+ only re-points the config + re-signs. Returns True on success (or when+ already configured), False on failure. Never raises.+ """+ 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")+ existing = subprocess.run(+ [security, "find-identity", "-p", "codesigning"],+ capture_output=True, text=True, check=False,+ )+ already_imported = identity in f"{existing.stdout}\n{existing.stderr}"++ if not already_imported:+ # Create a self-signed code-signing cert (valid 10 years) and import it+ # into the login keychain with codesign access so signing works without+ # an interactive unlock prompt.+ 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,+ )+ subprocess.run(+ [+ openssl, "pkcs12", "-export",+ "-inkey", str(key), "-in", str(crt),+ "-out", str(p12), "-passout", "pass:hermeslocal",+ ],+ capture_output=True, check=True,+ )+ imported = subprocess.run(+ [+ security, "import", str(p12), "-k", keychain,+ "-P", "hermeslocal",+ "-T", codesign, "-T", "/usr/bin/codesign_allocate",+ ],+ capture_output=True, text=True, check=False,+ )+ if imported.returncode != 0:+ print(f" (could not import signing identity into keychain: {imported.stderr.strip()})")+ return False+ print(f" → created and imported self-signed identity: {identity!r}")+ except Exception as exc:+ print(f" (certificate creation failed: {exc})")+ return False+ finally:+ shutil.rmtree(tmp_dir, ignore_errors=True)+ else:+ print(f" → identity {identity!r} already in keychain")++ # Point Hermes at the identity (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++ # Re-sign the packaged app so the current build already uses the identity.+ 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 _force_adhoc_macos_signing(env: dict, *, source_mode: bool) -> bool:"""Stop electron-builder grabbing a random keychain identity on self-update.@@ -8080,6 +8202,13 @@ def cmd_gui(args: argparse.Namespace):skip_build = getattr(args, "skip_build", False)force_build = getattr(args, "force_build", False)+ # 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):+ identity = getattr(args, "identity", None) or "Hermes Local Signing"+ ok = _desktop_macos_setup_tcc_identity(identity)+ sys.exit(0 if ok else 1)+packaged_executable = _desktop_packaged_executable(desktop_dir)if source_mode or not skip_build:diff --git a/hermes_cli/subcommands/gui.py b/hermes_cli/subcommands/gui.pyindex b51ff4b5ff9..ec10ef117e3 100644--- a/hermes_cli/subcommands/gui.py+++ b/hermes_cli/subcommands/gui.py@@ -60,4 +60,21 @@ def build_gui_parser(subparsers, *, cmd_gui: Callable) -> None:action="store_true",help="Force a full rebuild even if the content stamp matches",)+ gui_parser.add_argument(+ "--setup-tcc-identity",+ action="store_true",+ help=(+ "macOS only: create/import a self-signed code-signing certificate "+ "in the login keychain and point desktop.macos_signing_identity at "+ "it, then re-sign the packaged app. Makes macOS TCC grants (Full "+ "Disk Access, Accessibility, Files and Folders, microphone) survive "+ "rebuilds with a certificate-anchored identity. Idempotent — safe "+ "to re-run after updates."+ ),+ )+ gui_parser.add_argument(+ "--identity",+ default="Hermes Local Signing",+ help="Certificate name to create/use for --setup-tcc-identity (default: Hermes Local Signing)",+ )gui_parser.set_defaults(func=cmd_gui)diff --git a/tests/hermes_cli/test_gui_command.py b/tests/hermes_cli/test_gui_command.pyindex 42cdb459a44..7154f9eb4a7 100644--- a/tests/hermes_cli/test_gui_command.py+++ b/tests/hermes_cli/test_gui_command.py@@ -57,6 +57,8 @@ def _ns(**kw):ignore_existing=False,hermes_root=None,cwd=None,+ setup_tcc_identity=False,+ identity=None,)defaults.update(kw)return argparse.Namespace(**defaults)@@ -490,6 +492,109 @@ def test_relaunchable_fixup_falls_back_to_legacy_adhoc_on_failure(tmp_path, monkassert ["/usr/bin/codesign", "--force", "--deep", "--sign", "-", str(app)] in calls+# --- desktop --setup-tcc-identity ------------------------------------------+++def _fake_proc(cmd, returncode=0, stdout="", stderr=""):+ return subprocess.CompletedProcess(cmd, returncode, stdout=stdout, stderr=stderr)+++def test_setup_tcc_identity_creates_cert_imports_and_configures(tmp_path, monkeypatch, capsys):+ """Fresh identity: openssl generates, security imports, config is written."""+ monkeypatch.setattr(cli_main.sys, "platform", "darwin")+ monkeypatch.setattr(+ cli_main.shutil,+ "which",+ lambda name: {"openssl": "/usr/bin/openssl", "security": "/usr/bin/security", "codesign": "/usr/bin/codesign"}.get(name),+ )+ monkeypatch.setattr(cli_main.Path, "home", classmethod(lambda cls: tmp_path))++ identity = "Hermes Local Signing"+ calls = []++ def fake_run(cmd, **kwargs):+ calls.append(list(cmd))+ # `security find-identity` on first run reports no matching identity.+ if cmd[:3] == ["/usr/bin/security", "find-identity", "-p"]:+ return _fake_proc(cmd, stdout=" 0 identities found")+ return _fake_proc(cmd)++ monkeypatch.setattr(cli_main.subprocess, "run", fake_run)+ monkeypatch.setattr(cli_main, "_desktop_packaged_executable", lambda d: None)+ monkeypatch.setattr(cli_main, "_desktop_macos_relaunchable_fixup", lambda d: True)+ # Avoid writing the real user config.+ monkeypatch.setattr("hermes_cli.config.set_config_value", lambda key, value: None)++ assert cli_main._desktop_macos_setup_tcc_identity(identity) is True++ out = capsys.readouterr().out+ assert "created and imported self-signed identity" in out+ assert "set desktop.macos_signing_identity" in out+ # openssl cert generation + pkcs12 export + security import all ran.+ assert any(c[0] == "/usr/bin/openssl" and "req" in c for c in calls)+ assert any(c[0] == "/usr/bin/openssl" and "pkcs12" in c for c in calls)+ assert any(c[0] == "/usr/bin/security" and c[1] == "import" for c in calls)+ # Temp files cleaned up.+ assert not list(tmp_path.glob("hermes-tcc-*"))+++def test_setup_tcc_identity_skips_generation_when_already_present(tmp_path, monkeypatch, capsys):+ """Idempotent: an existing identity is reused, not regenerated."""+ monkeypatch.setattr(cli_main.sys, "platform", "darwin")+ monkeypatch.setattr(+ cli_main.shutil,+ "which",+ lambda name: {"openssl": "/usr/bin/openssl", "security": "/usr/bin/security", "codesign": "/usr/bin/codesign"}.get(name),+ )+ monkeypatch.setattr(cli_main.Path, "home", classmethod(lambda cls: tmp_path))++ calls = []++ def fake_run(cmd, **kwargs):+ calls.append(list(cmd))+ if cmd[:3] == ["/usr/bin/security", "find-identity", "-p"]:+ return _fake_proc(cmd, stdout=' "Hermes Local Signing" (CSSMERR_TP_NOT_TRUSTED)')+ return _fake_proc(cmd)++ monkeypatch.setattr(cli_main.subprocess, "run", fake_run)+ monkeypatch.setattr(cli_main, "_desktop_packaged_executable", lambda d: None)+ monkeypatch.setattr(cli_main, "_desktop_macos_relaunchable_fixup", lambda d: True)+ monkeypatch.setattr("hermes_cli.config.set_config_value", lambda key, value: None)++ assert cli_main._desktop_macos_setup_tcc_identity("Hermes Local Signing") is True++ out = capsys.readouterr().out+ assert "already in keychain" in out+ # No openssl generation, no security import — only find-identity + config.+ assert not any(c[0] == "/usr/bin/openssl" for c in calls)+ assert not any(c[0] == "/usr/bin/security" and c[1] == "import" for c in calls)+++def test_setup_tcc_identity_non_macos_skips(tmp_path, monkeypatch, capsys):+ """On non-macOS the setup is a no-op failure (not a crash)."""+ monkeypatch.setattr(cli_main.sys, "platform", "linux")++ assert cli_main._desktop_macos_setup_tcc_identity() is False+ assert "macOS-only" in capsys.readouterr().out+++def test_cmd_gui_setup_tcc_identity_exits_before_build(tmp_path, monkeypatch):+ """`hermes desktop --setup-tcc-identity` calls the setup and exits 0/1+ without building or launching the app."""+ root = _make_desktop_tree(tmp_path)+ monkeypatch.setattr(cli_main, "PROJECT_ROOT", root)+ _make_packaged_executable(root, monkeypatch, platform="darwin")++ with patch("hermes_cli.main._desktop_macos_setup_tcc_identity", return_value=True) as mock_setup, \+ patch("hermes_cli.main._run_npm_install_deterministic") as mock_install, \+ pytest.raises(SystemExit) as exc:+ cli_main.cmd_gui(_ns(setup_tcc_identity=True, identity="Hermes Local Signing"))++ assert exc.value.code == 0+ mock_setup.assert_called_once_with("Hermes Local Signing")+ mock_install.assert_not_called()++# --- desktop.* launch options (config.yaml) -------------------------------diff --git a/website/docs/user-guide/desktop.md b/website/docs/user-guide/desktop.mdindex ea59f042d71..1a5e2b06bf1 100644--- a/website/docs/user-guide/desktop.md+++ b/website/docs/user-guide/desktop.md@@ -548,13 +548,25 @@ box.For the strongest guarantee — a certificate-anchored identity, the samemechanism yabai/skhd users rely on — create a self-signed code-signing-certificate once and tell Hermes to use it:+certificate once and tell Hermes to use it. The one-shot command does+everything (creates the certificate in your login keychain, grants `codesign`+access, writes the config, and re-signs the packaged app):++```bash+hermes desktop --setup-tcc-identity+```++Or do it manually:1. Keychain Access → Certificate Assistant → **Create a Certificate…**2. Name: `Hermes Local Signing`, Identity Type: *Self-Signed Root*,Certificate Type: **Code Signing**.3. `hermes config set desktop.macos_signing_identity "Hermes Local Signing"`+Use `--identity <name>` with the command to create/use a differently named+certificate (default: `Hermes Local Signing`). The command is idempotent —+re-run it after updates to re-point the config and re-sign the rebuilt app.+The next update re-signs the rebuilt app with that certificate; every TCC grantsurvives. No Apple Developer account is required. Notarized release builds aredetected and never re-signed.