Branchwell

Jotley / app · jotley.ai / scripts / release-local-delivery.py

1#!/usr/bin/env python3
2"""Deliver locally built Jotley releases using Bitwarden Secrets Manager."""
3
4import argparse
5import hashlib
6import json
7import os
8from pathlib import Path
9import plistlib
10import re
11import subprocess
12import tempfile
13import time
14from contextlib import contextmanager
15from email.utils import formatdate
16from typing import Any, Iterator
17from urllib.error import HTTPError
18from urllib.parse import urlencode
19from urllib.request import Request, urlopen
20import xml.etree.ElementTree as ET
21from zipfile import ZipFile
22
23
24class Secrets:
25 def __init__(self) -> None:
26 self.environment = os.environ.copy()
27 if not self.environment.get("BWS_ACCESS_TOKEN"):
28 self.environment["BWS_ACCESS_TOKEN"] = subprocess.check_output(
29 ["launchctl", "getenv", "BWS_ACCESS_TOKEN"], text=True
30 ).strip()
31 self.ids = {}
32 for item in self.read("secret", "list"):
33 self.ids.setdefault(item["key"], []).append(item["id"])
34
35 def read(self, *args: str) -> Any:
36 result = subprocess.run(["bws", *args, "-o", "json"], env=self.environment, capture_output=True)
37 if result.returncode:
38 raise SystemExit("Bitwarden Secrets Manager access failed. Check bws and the machine account.")
39 return json.loads(result.stdout)
40
41 def get(self, name: str) -> str:
42 ids = self.ids.get(name, [])
43 if len(ids) != 1:
44 raise SystemExit(f"Expected one accessible Bitwarden Secrets Manager entry named {name}.")
45 return self.read("secret", "get", ids[0])["value"].strip()
46
47
48@contextmanager
49def apple_credentials(store: Secrets) -> Iterator[tuple[str, str, Path]]:
50 prefix = os.environ.get("JOTLEY_ASC_SECRET_PREFIX", "INKSPRING_ASC_UPLOAD")
51 key_id = store.get(prefix + "_KEY_ID")
52 issuer = store.get(prefix + "_ISSUER_ID")
53 with tempfile.TemporaryDirectory() as temporary:
54 key = Path(temporary) / f"AuthKey_{key_id}.p8"
55 key.touch(mode=0o600)
56 key.write_text(store.get(prefix + "_PRIVATE_KEY").replace("\\n", "\n") + "\n")
57 yield key_id, issuer, key
58
59
60def notarize(archive: Path, receipt: Path, store: Secrets) -> None:
61 with apple_credentials(store) as (key_id, issuer, key), receipt.open("w") as output:
62 subprocess.run(["xcrun", "notarytool", "submit", str(archive), "--key", str(key),
63 "--key-id", key_id, "--issuer", issuer, "--wait", "--timeout", "12m",
64 "--output-format", "json"], stdout=output, check=True)
65 result = json.loads(receipt.read_text())
66 if result["status"] != "Accepted":
67 raise SystemExit(f"Notarization {result['status']}. See {receipt}.")
68 print(f"Notarization accepted for {archive.name}.")
69
70
71def apple_api(endpoint: str, key_id: str, issuer: str, key: Path,
72 token_cache: dict[str, Any], data: Any = None) -> Any:
73 now = int(time.time())
74 if now >= token_cache.get("refresh_at", 0):
75 signer = """
76const { sign } = require('node:crypto');
77const { readFileSync } = require('node:fs');
78const [file, kid, iss, iat] = process.argv.slice(1);
79const encode = (value) => Buffer.from(JSON.stringify(value)).toString('base64url');
80const body = encode({ alg: 'ES256', kid, typ: 'JWT' }) + '.' +
81 encode({ iss, iat: Number(iat), exp: Number(iat) + 900, aud: 'appstoreconnect-v1' });
82const sig = sign('sha256', Buffer.from(body), { key: readFileSync(file), dsaEncoding: 'ieee-p1363' });
83process.stdout.write(body + '.' + sig.toString('base64url'));
84"""
85 token_cache.update(token=subprocess.check_output(
86 ["node", "-e", signer, str(key), key_id, issuer, str(now)], text=True
87 ), refresh_at=now + 840)
88 body = json.dumps({"data": data}).encode() if data is not None else None
89 request = Request("https://api.appstoreconnect.apple.com/v1/" + endpoint, data=body, headers={
90 "Authorization": "Bearer " + token_cache["token"], "Content-Type": "application/json"
91 })
92 try:
93 with urlopen(request, timeout=30) as response:
94 return json.load(response)["data"] if response.status != 204 else None
95 except HTTPError as error:
96 raise SystemExit(f"App Store Connect returned HTTP {error.code} for {endpoint}.") from None
97
98
99def testflight(archive: Path, app: str, group_name: str, resume: bool, store: Secrets) -> None:
100 with ZipFile(archive) as package:
101 (plist,) = [name for name in package.namelist() if re.fullmatch(r"Payload/[^/]+\.app/Info\.plist", name)]
102 info = plistlib.loads(package.read(plist))
103 number, version = info["CFBundleVersion"], info["CFBundleShortVersionString"]
104 query = urlencode({"filter[app]": app, "filter[version]": number, "limit": 20})
105 with apple_credentials(store) as (key_id, issuer, key):
106 token_cache: dict[str, Any] = {}
107
108 def api(endpoint: str, data: Any = None) -> Any:
109 return apple_api(endpoint, key_id, issuer, key, token_cache, data)
110
111 def matching_build() -> Any:
112 for row in api("builds?" + query):
113 attributes = api(f"builds/{row['id']}/preReleaseVersion")["attributes"]
114 if attributes["platform"] == "IOS" and attributes["version"] == version:
115 return row
116 return None
117
118 listing = api("apps/" + app)["attributes"]
119 if listing["bundleId"] != info["CFBundleIdentifier"]:
120 raise SystemExit("The archive does not match the requested App Store listing.")
121 (group,) = [item for item in api(f"apps/{app}/betaGroups?limit=200")
122 if item["attributes"]["name"] == group_name and item["attributes"]["isInternalGroup"]]
123 if not matching_build() and not resume:
124 subprocess.run(["xcrun", "altool", "--upload-app", "-f", str(archive), "-t", "ios",
125 "--apiKey", key_id, "--apiIssuer", issuer],
126 env={**os.environ, "API_PRIVATE_KEYS_DIR": str(key.parent)}, check=True)
127 for _ in range(90):
128 row = matching_build()
129 if row and row["attributes"]["processingState"] == "VALID":
130 break
131 if row and row["attributes"]["processingState"] in {"INVALID", "FAILED"}:
132 raise SystemExit(f"Apple could not process build {number}.")
133 time.sleep(10)
134 else:
135 raise SystemExit("Apple is still processing. Re-run with --resume to check it without uploading again.")
136 build_id = row["id"]
137 memberships = f"betaGroups/{group['id']}/relationships/builds"
138 def in_group() -> bool:
139 return group["attributes"]["hasAccessToAllBuilds"] or any(
140 item["id"] == build_id for item in api(memberships + "?limit=200")
141 )
142
143 if not in_group():
144 api(memberships, [{"type": "builds", "id": build_id}])
145 for _ in range(40):
146 beta = api(f"builds/{build_id}/buildBetaDetail")["attributes"]
147 if beta["internalBuildState"] == "IN_BETA_TESTING" and in_group():
148 print(f"{version} ({number}) verified in TestFlight for {group_name}.")
149 return
150 time.sleep(5)
151 raise SystemExit("Apple has yet to confirm internal testing. Check build status before retrying.")
152
153
154def mac_stage(args: argparse.Namespace, store: Secrets) -> None:
155 archive = args.archive.resolve()
156 info = plistlib.loads((args.app / "Contents/Info.plist").read_bytes())
157 version, build = info["CFBundleShortVersionString"], info["CFBundleVersion"]
158 if archive.name != f"Jotley-{version}-{build}.dmg" or info.get("SUFeedURL") != "https://jotley.ai/appcast.xml":
159 raise SystemExit("The installer filename, Mac app version, and production Sparkle feed must match.")
160 subprocess.run(["xcrun", "stapler", "validate", str(archive)], check=True)
161 subprocess.run(["codesign", "--verify", "--deep", "--strict", str(args.app)], check=True)
162 if args.signature:
163 signature = args.signature.read_text().strip()
164 else:
165 if not args.sign_tool:
166 raise SystemExit("Supply --sign-tool for a local signature or --signature for a verified Actions artifact.")
167 signed = subprocess.run([str(args.sign_tool.resolve()), "--ed-key-file", "-", str(archive)], text=True,
168 input=store.get(args.sparkle_secret) + "\n", capture_output=True, check=True)
169 match = re.search(r'sparkle:edSignature="([^"]+)"', signed.stdout)
170 if not match:
171 raise SystemExit("Sparkle signing did not return a signature.")
172 signature = match.group(1)
173 verify = """
174const { createPublicKey, verify } = require('node:crypto');
175const { readFileSync } = require('node:fs');
176const [file, publicKey, signature] = process.argv.slice(1);
177const key = createPublicKey({ key: Buffer.concat([Buffer.from('302a300506032b6570032100', 'hex'),
178 Buffer.from(publicKey, 'base64')]), type: 'spki', format: 'der' });
179if (!verify(null, readFileSync(file), key, Buffer.from(signature, 'base64'))) process.exit(1);
180"""
181 subprocess.run(["node", "-e", verify, str(archive), info["SUPublicEDKey"], signature], check=True)
182 endpoint = args.r2_endpoint.rstrip("/")
183 if not re.fullmatch(r"https://[a-f0-9]{32}\.r2\.cloudflarestorage\.com", endpoint):
184 raise SystemExit("Use the configured HTTPS Cloudflare R2 S3 endpoint.")
185 with archive.open("rb") as handle:
186 digest = hashlib.file_digest(handle, "sha256").hexdigest()
187 config = "user = " + json.dumps(store.get("CLOUDFLARE_R2_ACCESS_KEY_ID") + ":" +
188 store.get("CLOUDFLARE_R2_SECRET_ACCESS_KEY")) + "\n"
189 result = subprocess.run(["/usr/bin/curl", "-sS", "-K", "-", "--aws-sigv4", "aws:amz:auto:s3",
190 "--upload-file", str(archive), "--max-time", "180",
191 "--header", "If-None-Match: *", "--header", f"x-amz-content-sha256: {digest}",
192 "--header", "Content-Type: application/x-apple-diskimage",
193 "--header", f'Content-Disposition: attachment; filename="{archive.name}"',
194 "--output", os.devnull, "--write-out", "%{http_code}",
195 endpoint + "/jotley-media/downloads/" + archive.name],
196 input=config, capture_output=True, text=True, check=True)
197 if result.stdout not in {"200", "201", "412"}:
198 raise SystemExit(f"R2 upload returned HTTP {result.stdout}.")
199 url = "https://jotley.ai/" + archive.name
200 # The media host's bot filter rejects Python's default user agent.
201 check = Request(url + "?" + urlencode({"verify": digest[:16]}), headers={"User-Agent": "JotleyRelease/1.0"})
202 with urlopen(check, timeout=90) as response:
203 if hashlib.file_digest(response, "sha256").hexdigest() != digest:
204 raise SystemExit("The public download does not match the notarized installer.")
205 stage_website(args.output, archive, info, signature, digest, url, args.description)
206
207
208def stage_website(output: Path, archive: Path, info: dict[str, Any], signature: str,
209 digest: str, url: str, description: str) -> None:
210 version, build = info["CFBundleShortVersionString"], info["CFBundleVersion"]
211 size = archive.stat().st_size
212 output.mkdir(parents=True, exist_ok=False)
213 manifest = {"version": version, "build": int(build), "file": archive.name, "bytes": size, "sha256": digest}
214 (output / "mac-release.json").write_text(json.dumps(manifest, indent=2) + "\n")
215 sparkle = "http://www.andymatuschak.org/xml-namespaces/sparkle"
216 ET.register_namespace("sparkle", sparkle)
217 root = ET.Element("rss", {"version": "2.0"})
218 channel = ET.SubElement(root, "channel")
219 ET.SubElement(channel, "title").text = "Jotley"
220 item = ET.SubElement(channel, "item")
221 for key, value in {
222 "title": version, "pubDate": formatdate(usegmt=True), "description": description,
223 f"{{{sparkle}}}version": build, f"{{{sparkle}}}shortVersionString": version,
224 f"{{{sparkle}}}minimumSystemVersion": info["LSMinimumSystemVersion"]
225 }.items():
226 ET.SubElement(item, key).text = value
227 ET.SubElement(item, "enclosure", {"url": url, "length": str(size), "type": "application/octet-stream",
228 f"{{{sparkle}}}edSignature": signature})
229 ET.indent(root)
230 ET.ElementTree(root).write(output / "appcast.xml", encoding="utf-8", xml_declaration=True)
231 print(f"Verified {url}. Review the two website files in {output}.")
232
233
234def main() -> None:
235 parser = argparse.ArgumentParser(description=__doc__)
236 commands = parser.add_subparsers(dest="command", required=True)
237 notary = commands.add_parser("notarize")
238 notary.add_argument("archive", type=Path)
239 notary.add_argument("receipt", type=Path)
240 mobile = commands.add_parser("testflight")
241 mobile.add_argument("archive", type=Path)
242 mobile.add_argument("--app", default="6746770199")
243 mobile.add_argument("--group", default="Jotley Home")
244 mobile.add_argument("--resume", action="store_true")
245 mac = commands.add_parser("mac-stage")
246 mac.add_argument("archive", type=Path)
247 mac.add_argument("--app", type=Path, required=True)
248 mac.add_argument("--r2-endpoint", required=True)
249 mac.add_argument("--output", type=Path, required=True)
250 mac.add_argument("--description", required=True)
251 signature = mac.add_mutually_exclusive_group(required=True)
252 signature.add_argument("--sign-tool", type=Path)
253 signature.add_argument("--signature", type=Path)
254 mac.add_argument("--sparkle-secret", default="JOTLEY_SPARKLE_EDDSA_PRIVATE_KEY")
255 args = parser.parse_args()
256 store = Secrets()
257 if args.command == "notarize":
258 notarize(args.archive, args.receipt, store)
259 elif args.command == "testflight":
260 testflight(args.archive.resolve(), args.app, args.group, args.resume, store)
261 else:
262 mac_stage(args, store)
263
264
265if __name__ == "__main__":
266 main()