#!/usr/bin/env python3 """Configure Sparkle before signing and prepare full-only update publications.""" import argparse import base64 from pathlib import Path import plistlib import re import shutil import subprocess import tempfile from urllib.parse import urlsplit import xml.etree.ElementTree as ET SPARKLE = 'http://www.andymatuschak.org/xml-namespaces/sparkle' def validate_url(value, local=False): url = urlsplit(value) if not url.hostname or url.username or url.password or url.fragment or url.query: raise ValueError('Use an absolute update URL without credentials, query or fragment') if url.scheme != 'https' and not ( local and url.scheme == 'http' and url.hostname == 'localhost' ): raise ValueError('Updates require HTTPS (local testing permits http://localhost only)') return value def validate_key(value): if len(base64.b64decode(value, validate=True)) != 32: raise ValueError('Sparkle requires a base64-encoded 32-byte public key') return value def configure(app, feed, public_key, local=False): info_path = app / 'Contents/Info.plist' info = plistlib.loads(info_path.read_bytes()) if local and info['CFBundleIdentifier'] != 'app.cutdex.desktop.dev': raise ValueError('Local updates are restricted to the development app') info['DeskupAllowLocalHTTP'] = bool(local) info['SUFeedURL'] = validate_url(feed, local) info['SUPublicEDKey'] = validate_key(public_key) info['SUEnableAutomaticChecks'] = False info['SUAllowsAutomaticUpdates'] = False info['SUAutomaticallyUpdate'] = False if local: # Narrow ATS exception: no arbitrary network loads, never in production. ats = info.setdefault('NSAppTransportSecurity', {}) ats.setdefault('NSExceptionDomains', {})['localhost'] = { 'NSExceptionAllowsInsecureHTTPLoads': True, 'NSIncludesSubdomains': False, } info_path.write_bytes(plistlib.dumps(info)) def validate_app(app, local=False): info = plistlib.loads((app / 'Contents/Info.plist').read_bytes()) validate_url(info['SUFeedURL'], local) validate_key(info['SUPublicEDKey']) expected_id = 'app.cutdex.desktop.dev' if local else 'app.cutdex.desktop' if info['CFBundleIdentifier'] != expected_id: raise ValueError('Wrong application identity for this update channel') if not re.fullmatch(r'[0-9]+(?:\.[0-9]+){0,2}', info['CFBundleVersion']): raise ValueError('Use a monotonically increasing numeric build version') framework = app / 'Contents/Frameworks/Sparkle.framework' for file in ['Sparkle', 'Autoupdate', 'Updater.app/Contents/MacOS/Updater']: if not (framework / file).is_file(): raise ValueError(f'Missing Sparkle component: {file}') subprocess.run(['codesign', '--verify', '--deep', '--strict', str(app)], check=True) if not local: subprocess.run(['xcrun', 'stapler', 'validate', str(app)], check=True) subprocess.run(['spctl', '--assess', '--type', 'execute', str(app)], check=True) return info def version_key(version): if not re.fullmatch(r'[0-9]+(?:\.[0-9]+){0,2}', version): raise ValueError(f'Invalid numeric build version: {version}') parts = tuple(map(int, version.split('.'))) return parts + (0,) * (3 - len(parts)) def require_newer_build(output, version): feed = output / 'appcast.xml' if not feed.exists(): return items = ET.parse(feed).findall('./channel/item') for item in items: current = item.findtext(f'{{{SPARKLE}}}version') if current is None: enclosure = item.find('enclosure') current = None if enclosure is None else enclosure.get(f'{{{SPARKLE}}}version') if current is None: raise ValueError('Existing appcast item is missing its build version') if version_key(version) <= version_key(current): raise ValueError(f'New build {version} must be newer than published build {current}') def publish(app, output, base_url, tools, key_file=None, local=False): """Stage a complete publication; never mutate an existing version archive.""" validate_url(base_url, local) info = validate_app(app, local) output.mkdir(parents=True, exist_ok=True) require_newer_build(output, info['CFBundleVersion']) filename = f"cutdex-{info['CFBundleVersion']}-macos-arm64.zip" archive = output / filename if archive.exists(): raise ValueError(f'Refusing to replace published archive: {archive}') with tempfile.TemporaryDirectory(prefix='cutdex-update-') as directory: stage = Path(directory) subprocess.run(['ditto', '-c', '-k', '--sequesterRsrc', '--keepParent', str(app), str(stage / filename)], check=True) command = [str(tools / 'generate_appcast'), '--maximum-deltas', '0', '--download-url-prefix', base_url.rstrip('/') + '/', '-o', str(stage / 'appcast.xml')] if key_file: command.extend(['--ed-key-file', str(key_file)]) subprocess.run([*command, str(stage)], check=True) tree = ET.parse(stage / 'appcast.xml') if tree.findall(f'.//{{{SPARKLE}}}deltas'): raise ValueError('This release pipeline only permits full updates') enclosures = tree.findall('.//enclosure') if len(enclosures) != 1 or not enclosures[0].get(f'{{{SPARKLE}}}edSignature'): raise ValueError('Expected exactly one signed full update') # Upload archive first, appcast last. Local replacement is atomic too. shutil.copy2(stage / filename, archive) pending = output / 'appcast.xml.pending' shutil.copy2(stage / 'appcast.xml', pending) pending.replace(output / 'appcast.xml') return archive def main(): parser = argparse.ArgumentParser(description=__doc__) commands = parser.add_subparsers(dest='command', required=True) config = commands.add_parser('configure') config.add_argument('--app', type=Path, required=True) config.add_argument('--feed', required=True) config.add_argument('--public-key', required=True) config.add_argument('--local', action='store_true') release = commands.add_parser('publish') release.add_argument('--app', type=Path, required=True) release.add_argument('--output', type=Path, required=True) release.add_argument('--base-url', required=True) release.add_argument('--tools', type=Path, required=True, help='Sparkle bin directory') release.add_argument('--key-file', type=Path) release.add_argument('--local', action='store_true') args = parser.parse_args() if args.command == 'configure': configure(args.app, args.feed, args.public_key, args.local) else: print(publish(args.app, args.output, args.base_url, args.tools.resolve(), args.key_file, args.local)) if __name__ == '__main__': main()