Jotley / app · jotley.ai / scripts / signing_identity.py
| 1 | """Read-only, login-keychain-only preflight for local Mac signing.""" |
| 2 | import argparse |
| 3 | from pathlib import Path |
| 4 | import re |
| 5 | import subprocess |
| 6 | |
| 7 | |
| 8 | KINDS = {"development": "Apple Development", "developer-id": "Developer ID Application", "app-store": "Apple Distribution"} |
| 9 | |
| 10 | |
| 11 | def resolve_identity(listing: str, requested: str, kind: str | None = None) -> str: |
| 12 | matches = [] |
| 13 | for line in listing.splitlines(): |
| 14 | # Invalid/revoked identities have an error suffix; never select them. |
| 15 | match = re.fullmatch(r'\s*\d+\)\s+([A-Fa-f0-9]{40})\s+"([^"]+)"\s*', line) |
| 16 | if not match: |
| 17 | continue |
| 18 | fingerprint, name = match.groups() |
| 19 | if requested.casefold() == fingerprint.casefold() or requested == name or requested in KINDS.values() and name.startswith(requested + ":"): |
| 20 | matches.append((fingerprint, name)) |
| 21 | if not matches: |
| 22 | raise ValueError("Required signing identity is missing or invalid in ~/Library/Keychains/login.keychain-db. Import the existing identity into login and verify its authorization before signing. System keychain fallback is disabled.") |
| 23 | if len(matches) != 1: |
| 24 | raise ValueError("More than one matching identity is in login. Set the exact certificate name or SHA-1 fingerprint.") |
| 25 | fingerprint, name = matches[0] |
| 26 | if not any(name.startswith(prefix + ":") for prefix in KINDS.values()): |
| 27 | raise ValueError("Select an Apple Development, Developer ID Application or Apple Distribution identity for the app.") |
| 28 | if kind and not name.startswith(KINDS[kind] + ":"): |
| 29 | raise ValueError(f"This build requires a {KINDS[kind]} identity, not {name.split(':')[0]}.") |
| 30 | return fingerprint.upper() |
| 31 | |
| 32 | |
| 33 | def local_signing_identity(requested: str, kind: str | None = None) -> str: |
| 34 | keychain = Path.home() / "Library/Keychains/login.keychain-db" |
| 35 | result = subprocess.run(["/usr/bin/security", "find-identity", "-v", "-p", "codesigning", str(keychain)], capture_output=True, text=True) |
| 36 | if result.returncode: |
| 37 | raise ValueError("Could not inspect the login keychain. Unlock it using macOS, then retry; no System keychain fallback is allowed.") |
| 38 | return resolve_identity(result.stdout, requested, kind) |
| 39 | |
| 40 | |
| 41 | def main() -> None: |
| 42 | parser = argparse.ArgumentParser(description=__doc__) |
| 43 | parser.add_argument("identity") |
| 44 | parser.add_argument("--kind", choices=KINDS) |
| 45 | args = parser.parse_args() |
| 46 | try: |
| 47 | print(local_signing_identity(args.identity, args.kind)) |
| 48 | except ValueError as error: |
| 49 | parser.exit(1, f"Signing preflight: {error}\n") |
| 50 | |
| 51 | |
| 52 | if __name__ == "__main__": |
| 53 | main() |