~ knotless Search/
↑↓ move↵ open⇧↵ all results

geesawra.industries/hydraulophone

An unofficial YouTube Music app for iPhone, iPad, and Mac.

0
0
main
155 lines · 7.2 KB Raw History
#!/usr/bin/env python3
"""Archive the existing Catalyst app and produce an unnotarized development-signed DMG."""

from __future__ import annotations

import argparse
import hashlib
import os
from pathlib import Path
import plistlib
import re
import shutil
import subprocess
import sys
import tempfile


def fail(message: str) -> None:
    raise SystemExit(message)


def run(*arguments: str, capture: bool = False) -> str:
    result = subprocess.run(
        arguments, check=True, text=True, capture_output=capture
    )
    return result.stdout if capture else ""


def verify_app(app: Path, team: str) -> None:
    run("codesign", "--verify", "--deep", "--strict", str(app))
    display = subprocess.run(
        ["codesign", "--display", "--verbose=4", str(app)],
        check=True, text=True, capture_output=True,
    ).stderr
    if f"TeamIdentifier={team}\n" not in display:
        fail("The exported app was signed by a different team.")
    if "Authority=Apple Development:" not in display or "runtime" not in display:
        fail("The app must use Apple Development signing and hardened runtime.")
    entitlements = plistlib.loads(subprocess.run(
        ["codesign", "--display", "--entitlements", "-", "--xml", str(app)],
        check=True, capture_output=True,
    ).stdout)
    with (app / "Contents/Info.plist").open("rb") as file:
        bundle_id = plistlib.load(file)["CFBundleIdentifier"]
    groups = entitlements.get("keychain-access-groups", [])
    app_id = entitlements.get("com.apple.application-identifier")
    if not app_id or app_id not in groups:
        fail("The app is missing its signed application identifier/private Keychain group.")
    if entitlements.get("com.apple.developer.team-identifier") != team:
        fail("The app's signed team entitlement does not match its signing team.")
    if not any(isinstance(group, str) and group.endswith(f".{bundle_id}")
               and "$" not in group for group in groups):
        fail("The exported app is missing its resolved private Keychain access group.")
    if entitlements.get("get-task-allow") or entitlements.get("com.apple.security.get-task-allow"):
        fail("The exported app still contains a debug entitlement.")
    if entitlements.get("com.apple.developer.carplay-audio"):
        fail("The Mac app must not include the CarPlay entitlement.")


def main() -> None:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("version", help="Marketing version, e.g. 0.1.0")
    parser.add_argument("build", help="Build number, e.g. 1")
    args = parser.parse_args()
    if not re.fullmatch(r"\d+\.\d+\.\d+", args.version):
        fail("Version must contain three numbers, e.g. 0.1.0.")
    if not re.fullmatch(r"\d+(?:\.\d+){0,2}", args.build):
        fail("Build must contain one to three numbers, e.g. 1.")
    root = Path(__file__).resolve().parent.parent
    os.chdir(root)
    team = os.environ.get("HYDRAULOPHONE_DEVELOPMENT_TEAM", "").strip()
    if not team:
        team = run(sys.executable, str(root / "Scripts/read_development_team.py"), capture=True).strip()
    if not re.fullmatch(r"[A-Z0-9]{10}", team):
        fail("HYDRAULOPHONE_DEVELOPMENT_TEAM must be a ten-character Apple team ID.")

    output = root / ".build/releases"
    output.mkdir(parents=True, exist_ok=True)
    dmg = output / f"Hydraulophone-{args.version}-{args.build}.dmg"
    if dmg.exists():
        fail(f"Refusing to overwrite {dmg}; choose a new version/build or move the previous artifact.")
    work = Path(tempfile.mkdtemp(prefix=f"mac-{args.version}-{args.build}-", dir=output))
    print(f"Release work directory: {work}", flush=True)
    archive = work / "Hydraulophone.xcarchive"
    provisioning = []
    allow_updates = os.environ.get("HYDRAULOPHONE_ALLOW_PROVISIONING_UPDATES", "1")
    if allow_updates not in {"0", "1"}:
        fail("HYDRAULOPHONE_ALLOW_PROVISIONING_UPDATES must be 0 or 1.")
    if allow_updates == "1":
        provisioning = ["-allowProvisioningUpdates"]
    run(
        "xcodebuild", "archive", "-project", "Hydraulophone.xcodeproj",
        "-scheme", "Hydraulophone", "-configuration", "Release",
        "-destination", "platform=macOS,variant=Mac Catalyst",
        "-derivedDataPath", str(root / ".build/mac-dmg"), "-archivePath", str(archive),
        f"DEVELOPMENT_TEAM={team}", "CODE_SIGN_STYLE=Automatic",
        "CODE_SIGN_IDENTITY=Apple Development",
        "CODE_SIGNING_ALLOWED=YES", "CODE_SIGNING_REQUIRED=YES",
        "ENABLE_HARDENED_RUNTIME=YES", "ONLY_ACTIVE_ARCH=NO",
        "ARCHS=arm64", f"MARKETING_VERSION={args.version}",
        f"CURRENT_PROJECT_VERSION={args.build}", *provisioning,
    )
    archived_app = archive / "Products/Applications/Hydraulophone.app"
    if not archived_app.is_dir():
        fail(f"Xcode did not archive the expected app at {archived_app}.")
    stage = work / "dmg-root"
    stage.mkdir()
    app = stage / archived_app.name
    run("ditto", str(archived_app), str(app))

    # Keep Xcode's team, application ID, provisioning profile and Keychain group.
    # Remove debugger access from the packaged Release copy and sign it with
    # the exact certificate Xcode chose. The extracted certificate is public.
    certificate_prefix = work / "signing-certificate-"
    run("codesign", "--display", f"--extract-certificates={certificate_prefix}", str(app))
    identity = hashlib.sha1(Path(f"{certificate_prefix}0").read_bytes()).hexdigest()
    entitlements = plistlib.loads(subprocess.run(
        ["codesign", "--display", "--entitlements", "-", "--xml", str(app)],
        check=True, capture_output=True,
    ).stdout)
    entitlements.pop("get-task-allow", None)
    entitlements.pop("com.apple.security.get-task-allow", None)
    signing_entitlements = work / "SigningEntitlements.plist"
    signing_entitlements.write_bytes(plistlib.dumps(entitlements))
    run("codesign", "--force", "--sign", identity, "--options", "runtime",
        "--timestamp=none", "--entitlements", str(signing_entitlements), str(app))
    verify_app(app, team)
    executable = app / "Contents/MacOS/Hydraulophone"
    architectures = run("xcrun", "lipo", "-archs", str(executable), capture=True).split()
    if architectures != ["arm64"]:
        fail("The release executable must contain only the arm64 architecture.")

    run(sys.executable, str(root / "Scripts/check-mac-keychain"), str(app))

    (stage / "Applications").symlink_to("/Applications")
    for name in ("LICENSE", "NOTICE"):
        shutil.copy2(root / name, stage / name)
    candidate = work / dmg.name
    run("hdiutil", "create", "-volname", "Hydraulophone", "-srcfolder", str(stage),
        "-format", "UDZO", str(candidate))
    run("codesign", "--sign", identity, "--timestamp=none", str(candidate))
    run("codesign", "--verify", "--strict", str(candidate))
    run("hdiutil", "verify", str(candidate))
    # Publish without overwriting an artifact created by a concurrent run.
    os.link(candidate, dmg)
    candidate.unlink()
    print(f"Created unnotarized DMG: {dmg}\nArchive and signing records: {work}", flush=True)


if __name__ == "__main__":
    try:
        main()
    except (subprocess.CalledProcessError, OSError, ValueError) as error:
        print(f"Mac release failed: {error}", file=sys.stderr)
        raise SystemExit(1) from None