174 lines
9.3 KiB
Python
174 lines
9.3 KiB
Python
#!/usr/bin/env python3
|
|
"""Build and verify a local ad-hoc Release ZIP; does not publish or notarize."""
|
|
import argparse
|
|
import hashlib
|
|
from pathlib import Path
|
|
import plistlib
|
|
import re
|
|
import shutil
|
|
import subprocess
|
|
import tempfile
|
|
import zipfile
|
|
import xml.etree.ElementTree as ET
|
|
|
|
ROOT = Path(__file__).resolve().parents[1]
|
|
KEY_ACCOUNT = "cn.airnan.kymo"
|
|
RELEASES = "https://git.airnan.cn/wangairnan/Kymo/releases/download"
|
|
|
|
|
|
def run(command):
|
|
result = subprocess.run([str(v) for v in command], cwd=ROOT, capture_output=True)
|
|
if result.returncode:
|
|
raise RuntimeError(result.stdout.decode(errors="replace")[-5000:] + result.stderr.decode(errors="replace")[-5000:])
|
|
return result
|
|
|
|
|
|
def verify(app):
|
|
run(["codesign", "--verify", "--deep", "--strict", app])
|
|
info = plistlib.loads((app / "Contents/Info.plist").read_bytes())
|
|
identifier = info["CFBundleIdentifier"]
|
|
installer = app / "Contents/Frameworks/Sparkle.framework/Versions/B/XPCServices/Installer.xpc"
|
|
if not installer.is_dir() or not info.get("SUEnableInstallerLauncherService"):
|
|
raise RuntimeError("Missing Sparkle sandbox installer")
|
|
for target in [app, app / "Contents/XPCServices/SMARTService.xpc"]:
|
|
details = run(["codesign", "-dvvv", target]).stderr.decode()
|
|
if "Signature=adhoc" not in details or "runtime)" not in details:
|
|
raise RuntimeError("Expected ad-hoc signature with Hardened Runtime: " + str(target))
|
|
signed = run(["codesign", "-d", "--entitlements", "-", "--xml", target])
|
|
entitlements = plistlib.loads(signed.stdout)
|
|
expected = {"com.apple.security.app-sandbox": True,
|
|
"com.apple.security.network.client": True,
|
|
"com.apple.security.files.user-selected.read-only": True,
|
|
"com.apple.security.cs.disable-library-validation": True,
|
|
"com.apple.security.temporary-exception.mach-lookup.global-name":
|
|
[identifier + "-spks", identifier + "-spki"]} if target == app else {}
|
|
if entitlements != expected:
|
|
raise RuntimeError("Unexpected release entitlements: " + str(target))
|
|
# With no Team ID, Hardened Runtime uses an explicit allowlist of Sparkle code hashes.
|
|
# Validate both the signed host constraints and every shipped architecture after embedding.
|
|
pinned = plistlib.loads((ROOT / "Config/Sparkle-library-constraint.plist").read_bytes())
|
|
hashes = {value.hex() for value in pinned["cdhash"]["$in"]}
|
|
details = run(["codesign", "-dvvvv", app])
|
|
constraints = (details.stdout + details.stderr).decode()
|
|
if "Has Library Load Constraints" not in constraints or any(h not in constraints for h in hashes):
|
|
raise RuntimeError("Host signature is missing the Sparkle library constraint")
|
|
framework = app / "Contents/Frameworks/Sparkle.framework"
|
|
for arch in run(["lipo", "-archs", framework / "Sparkle"]).stdout.decode().split():
|
|
signature = run(["codesign", "-dvvv", "--arch", arch, framework]).stderr.decode()
|
|
digest = re.search(r"^CDHash=([0-9a-f]+)$", signature, re.MULTILINE)
|
|
if not digest or digest[1] not in hashes:
|
|
raise RuntimeError(f"Embedded Sparkle signature for {arch} does not match the library constraint")
|
|
for path in app.rglob("*"):
|
|
if path.name in {".DS_Store", ".git", "xcuserdata"} or path.suffix in {".swift", ".xcstrings", ".md", ".py", ".dSYM"}:
|
|
raise RuntimeError("Development file in application: " + str(path))
|
|
|
|
|
|
def archive_info(package):
|
|
with zipfile.ZipFile(package) as archive:
|
|
if any(not item.filename.startswith("kymo.app/") or ".." in Path(item.filename).parts
|
|
for item in archive.infolist()):
|
|
raise RuntimeError("Unexpected archive contents")
|
|
return plistlib.loads(archive.read("kymo.app/Contents/Info.plist"))
|
|
|
|
|
|
def generate_feed(package, info, tools):
|
|
public_key = run([tools / "generate_keys", "--account", KEY_ACCOUNT, "-p"]).stdout.decode().strip()
|
|
if public_key != info["SUPublicEDKey"]:
|
|
raise RuntimeError("Release key does not match the public key embedded in Kymo")
|
|
prefix = f"{RELEASES}/v{info['CFBundleShortVersionString']}/"
|
|
run([tools / "generate_appcast", "--account", KEY_ACCOUNT, "--download-url-prefix", prefix,
|
|
"--maximum-deltas", "0", package.parent])
|
|
feed = package.parent / "appcast.xml"
|
|
item = ET.parse(feed).find("./channel/item")
|
|
ns = "{http://www.andymatuschak.org/xml-namespaces/sparkle}"
|
|
enclosure = item.find("enclosure") if item is not None else None
|
|
if (enclosure is None or enclosure.get("url") != prefix + package.name
|
|
or enclosure.get("length") != str(package.stat().st_size)
|
|
or item.findtext(ns + "version") != info["CFBundleVersion"]):
|
|
raise RuntimeError("Appcast does not describe the final release ZIP")
|
|
verify_signature = [tools / "sign_update", "--account", KEY_ACCOUNT, "--verify"]
|
|
run([*verify_signature, package, enclosure.attrib[ns + "edSignature"]])
|
|
run([*verify_signature, feed])
|
|
return feed
|
|
|
|
|
|
def sign_existing(package, work):
|
|
package = package.expanduser().resolve(strict=True)
|
|
feed = package.parent / "appcast.xml"
|
|
if feed.exists():
|
|
raise RuntimeError("appcast.xml already exists in this directory")
|
|
info = archive_info(package)
|
|
trusted = plistlib.loads((ROOT / "Config/Kymo-Info.plist").read_bytes())
|
|
if info.get("CFBundleIdentifier") != KEY_ACCOUNT or info.get("SUPublicEDKey") != trusted["SUPublicEDKey"]:
|
|
raise RuntimeError("ZIP is not a Kymo build for this Sparkle signing key")
|
|
archives = work / "archives"
|
|
archives.mkdir()
|
|
staged = archives / package.name
|
|
shutil.copyfile(package, staged)
|
|
run(["ditto", "-x", "-k", staged, work / "unpacked"])
|
|
verify(work / "unpacked/kymo.app")
|
|
run(["xcodebuild", "-resolvePackageDependencies", "-project", "kymo.xcodeproj", "-scheme", "kymo",
|
|
"-derivedDataPath", work / "build"])
|
|
signed = generate_feed(staged, info, work / "build/SourcePackages/artifacts/sparkle/Sparkle/bin")
|
|
if staged.read_bytes() != package.read_bytes():
|
|
raise RuntimeError("ZIP changed while generating its appcast")
|
|
with feed.open("xb") as result:
|
|
result.write(signed.read_bytes())
|
|
print("Signed appcast:", feed)
|
|
|
|
|
|
def main():
|
|
parser = argparse.ArgumentParser(description=__doc__)
|
|
parser.add_argument("--output", type=Path, default=ROOT / "dist", help="Output directory (existing ZIPs are preserved)")
|
|
mode = parser.add_mutually_exclusive_group()
|
|
mode.add_argument("--sign-existing", type=Path, metavar="ZIP", help="Generate appcast.xml beside an existing Kymo release ZIP")
|
|
mode.add_argument("--zip-only", action="store_true", help="Build a local test ZIP without a signing key or appcast")
|
|
args = parser.parse_args()
|
|
with tempfile.TemporaryDirectory(prefix="kymo-release-") as temp:
|
|
work = Path(temp)
|
|
if args.sign_existing:
|
|
sign_existing(args.sign_existing, work)
|
|
return
|
|
print("Building ordinary ad-hoc Release…", flush=True)
|
|
run(["xcodebuild", "-project", "kymo.xcodeproj", "-scheme", "kymo", "-configuration", "Release",
|
|
"-derivedDataPath", work / "build", "SWIFT_EMIT_LOC_STRINGS=NO", "SWIFT_ACTIVE_COMPILATION_CONDITIONS=",
|
|
"CODE_SIGN_IDENTITY=-", "build"])
|
|
app = work / "build/Build/Products/Release/kymo.app"
|
|
verify(app)
|
|
info = plistlib.loads((app / "Contents/Info.plist").read_bytes())
|
|
architectures = run(["lipo", "-archs", app / "Contents/MacOS/kymo"]).stdout.decode().strip().replace(" ", "-")
|
|
name = "kymo-{}-{}-{}-adhoc.zip".format(info["CFBundleShortVersionString"], info["CFBundleVersion"], architectures)
|
|
archives = work / "archives"
|
|
archives.mkdir()
|
|
package = archives / name
|
|
run(["ditto", "-c", "-k", "--keepParent", "--norsrc", "--noextattr", app, package])
|
|
archive_info(package)
|
|
unpacked = work / "unpacked"
|
|
run(["ditto", "-x", "-k", package, unpacked])
|
|
verify(unpacked / "kymo.app")
|
|
output = args.output.expanduser().resolve()
|
|
output.mkdir(parents=True, exist_ok=True)
|
|
destination = output / name
|
|
checksum = output / (name + ".sha256")
|
|
if destination.exists() or checksum.exists() or (not args.zip_only and (output / "appcast.xml").exists()):
|
|
raise RuntimeError("Output already exists; choose another --output directory")
|
|
feed = None if args.zip_only else generate_feed(package, info, work / "build/SourcePackages/artifacts/sparkle/Sparkle/bin")
|
|
digest = hashlib.sha256(package.read_bytes()).hexdigest()
|
|
shutil.copy2(package, destination)
|
|
checksum.write_text(digest + " " + name + "\n")
|
|
if feed:
|
|
shutil.copy2(feed, output / feed.name)
|
|
print("Signed appcast:", output / feed.name)
|
|
print("PASS: original and extracted app signatures, runtime, entitlements and archive contents")
|
|
print("Minimum macOS:", info.get("LSMinimumSystemVersion"), "architectures:", architectures)
|
|
print("ZIP:", destination, "bytes:", destination.stat().st_size)
|
|
print("SHA256:", digest)
|
|
print("Not notarized; not verified under default Gatekeeper policy on another Mac.")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
try:
|
|
main()
|
|
except (OSError, ValueError, RuntimeError, subprocess.SubprocessError) as error:
|
|
raise SystemExit(str(error))
|