SPB Git

Repository Public

provision.py 7.4 KB 100 lines python

1#!/usr/bin/env python32# Author: Simon-Pierre Boucher — contact@spboucher.ai3# File: Scripts/provision.py4# Description: Registers SP Mail's bundle identifiers — the two apps and their extensions (widgets, share extension, notification service) —5# with their capabilities, and creates the Developer ID provisioning profiles of the Mac app and of each Mac extension, with the EXISTING6# App Store Connect API key and Developer ID certificate. Nothing here goes through the Apple Developer website.7#8# Idempotent: existing resources are reused; no certificate is ever created; nothing secret is printed.9#   Scripts/provision.py --check    dry run: reports what exists and what WOULD be created, changes nothing at Apple10#   Scripts/provision.py            creates what is missing11# The iOS targets are signed automatically at archive time (Scripts/ios-archive.sh, -allowProvisioningUpdates with the same API key): this12# script only makes sure their App IDs exist with the right capabilities.13#14# App Groups: the App Store Connect API can turn the APP_GROUPS capability on for an App ID, but it has no resource for the group15# identifier itself — it can neither create `group.ai.spboucher.spmail` nor attach it to an App ID. macOS does not need it (the apps use16# the Team-ID-prefixed group `3YM54G49SN.group.ai.spboucher.spmail`, valid without registration under Developer ID). On iOS see17# docs/SYSTEM-INTEGRATION.md § App Group.18import base64, hashlib, os, subprocess, sys19sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))20import asc2122CHECK = "--check" in sys.argv23OUT = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "Build", "profiles")24APP_CAPS = ["ASSOCIATED_DOMAINS", "PUSH_NOTIFICATIONS"]25# identifier, display name, platform, capabilities, Developer ID profile name (Mac only), profile file26TARGETS = [27    ("ai.spboucher.spmail", "SP Mail", "MAC_OS", APP_CAPS, "SP Mail Developer ID", "SPMail.provisionprofile"),28    ("ai.spboucher.spmail.widgets", "SP Mail Widgets", "MAC_OS", [], "SP Mail Widgets Developer ID", "SPMailWidgets.provisionprofile"),29    ("ai.spboucher.spmail.share", "SP Mail Share", "MAC_OS", [], "SP Mail Share Developer ID", "SPMailShare.provisionprofile"),30    ("ai.spboucher.spmail.notifications", "SP Mail Notifications", "MAC_OS", [], "SP Mail Notifications Developer ID", "SPMailNotifications.provisionprofile"),31    # iOS: APP_GROUPS on the app and on every extension (shared container). « Communication Notifications » (sender avatar) is not a32    # capability type of the App Store Connect API (409 on POST /v1/bundleIdCapabilities): it cannot be enabled from here.33    ("ai.spboucher.spmail.ios", "SP Mail iOS", "IOS", APP_CAPS + ["APP_GROUPS"], None, None),34    ("ai.spboucher.spmail.ios.widgets", "SP Mail iOS Widgets", "IOS", ["APP_GROUPS"], None, None),35    ("ai.spboucher.spmail.ios.share", "SP Mail iOS Share", "IOS", ["APP_GROUPS"], None, None),36    ("ai.spboucher.spmail.ios.notifications", "SP Mail iOS Notifications", "IOS", ["APP_GROUPS"], None, None),37]3839def bundle(identifier, name, platform):40    s, d = asc.call("GET", f"/v1/bundleIds?filter[identifier]={identifier}&limit=50")41    ids = [b for b in d.get("data", []) if b["attributes"]["identifier"] == identifier]42    if ids: print("bundle id exists:", identifier); return ids[0]["id"]43    if CHECK: print("bundle id MISSING (would be created):", identifier); return None44    s, d = asc.call("POST", "/v1/bundleIds", {"data": {"type": "bundleIds", "attributes": {"identifier": identifier, "name": name, "platform": platform}}})45    if s >= 300: sys.exit(f"cannot create bundle id {identifier}: HTTP {s} {str(d)[:300]}")46    print("bundle id created:", identifier); return d["data"]["id"]4748def capabilities(bid, identifier, caps):49    s, d = asc.call("GET", f"/v1/bundleIds/{bid}/bundleIdCapabilities")50    have = [c["attributes"]["capabilityType"] for c in d.get("data", [])]51    changed = False52    for cap in caps:53        if cap in have: print(f"  capability present: {cap}"); continue54        if CHECK: print(f"  capability MISSING: {cap}"); continue55        s, d = asc.call("POST", "/v1/bundleIdCapabilities", {"data": {"type": "bundleIdCapabilities", "attributes": {"capabilityType": cap}, "relationships": {"bundleId": {"data": {"type": "bundleIds", "id": bid}}}}})56        if s >= 300: sys.exit(f"cannot enable {cap} on {identifier}: HTTP {s} {str(d)[:300]}")57        print(f"  capability enabled: {cap}"); changed = True58    return changed5960def developer_id_certificate():61    out = subprocess.run(["security", "find-certificate", "-a", "-c", "Developer ID Application", "-Z"], capture_output=True, text=True).stdout62    local = [l.split(":")[1].strip() for l in out.splitlines() if l.startswith("SHA-1")]63    if not local: sys.exit("no Developer ID Application certificate in the keychain")64    s, d = asc.call("GET", "/v1/certificates?filter[certificateType]=DEVELOPER_ID_APPLICATION,DEVELOPER_ID_APPLICATION_G2&limit=100")65    cert = next((c["id"] for c in d.get("data", []) if hashlib.sha1(base64.b64decode(c["attributes"]["certificateContent"])).hexdigest().upper() in local), None)66    if not cert: sys.exit("the keychain's Developer ID certificate is not visible through the API")67    return cert6869def profile(bid, name, file, replace):70    s, allp = asc.call("GET", "/v1/profiles?filter[profileType]=MAC_APP_DIRECT&limit=200")71    mine = [p for p in allp.get("data", []) if p["attributes"]["name"] == name]72    active = [p for p in mine if p["attributes"]["profileState"] == "ACTIVE"]73    if active and not replace: p = active[0]; print("profile exists:", name)74    elif CHECK: print(f"profile MISSING or stale (would be created): {name} -> Build/profiles/{file}"); return75    else:76        # a capability change on the App ID invalidates its profiles: the stale one is replaced77        for stale in mine: asc.call("DELETE", f"/v1/profiles/{stale['id']}"); print("  stale profile removed")78        s, d = asc.call("POST", "/v1/profiles", {"data": {"type": "profiles", "attributes": {"name": name, "profileType": "MAC_APP_DIRECT"}, "relationships": {79            "bundleId": {"data": {"type": "bundleIds", "id": bid}}, "certificates": {"data": [{"type": "certificates", "id": developer_id_certificate()}]}}}})80        if s >= 300: sys.exit(f"cannot create the profile {name}: HTTP {s} {str(d)[:300]}")81        p = d["data"]; print("profile created:", name)82    content = base64.b64decode(p["attributes"]["profileContent"])83    os.makedirs(OUT, exist_ok=True)84    open(os.path.join(OUT, file), "wb").write(content)85    for dest in ("~/Library/Developer/Xcode/UserData/Provisioning Profiles", "~/Library/MobileDevice/Provisioning Profiles"):86        dd = os.path.expanduser(dest); os.makedirs(dd, exist_ok=True)87        open(os.path.join(dd, p["attributes"]["uuid"] + ".provisionprofile"), "wb").write(content)88    print(f"  written: Build/profiles/{file} | uuid {p['attributes']['uuid']} | expires {p['attributes']['expirationDate'][:10]}")8990for identifier, display, platform, caps, profile_name, file in TARGETS:91    bid = bundle(identifier, display, platform)92    if not bid:93        # dry run on an identifier that does not exist yet: say what the real run would do94        for cap in caps: print(f"  capability WOULD be enabled: {cap}")95        if profile_name: print(f"profile WOULD be created: {profile_name} -> Build/profiles/{file}")96        continue97    changed = capabilities(bid, identifier, caps)98    if profile_name: profile(bid, profile_name, file, changed)99if CHECK: print("dry run: nothing was changed at Apple")100
Files main
Menu

Theme