"""Minimal App Store Connect API client (JWT with the .p8 key in ~/.appstoreconnect/private_keys). Used by the release/metadata scripts.""" import base64 import json import os import time import urllib.error import urllib.request from pathlib import Path from cryptography.hazmat.primitives import hashes, serialization from cryptography.hazmat.primitives.asymmetric import ec from cryptography.hazmat.primitives.asymmetric.utils import decode_dss_signature API = 'https://api.appstoreconnect.apple.com' KEY_ID = os.environ.get('ASC_KEY_ID', 'HGF8KY67BH') ISSUER = os.environ.get('ASC_ISSUER', '69a6de8c-48b0-47e3-e053-5b8c7c11a4d1') BUNDLE_ID = 'com.sagifer.skycontour.ios' def _b64url(b): return base64.urlsafe_b64encode(b).rstrip(b'=').decode() class AscError(RuntimeError): pass class Asc: def __init__(self, key_id=KEY_ID, issuer=ISSUER): self.key_id, self.issuer = key_id, issuer path = Path.home() / f'.appstoreconnect/private_keys/AuthKey_{key_id}.p8' self.key = serialization.load_pem_private_key(path.read_bytes(), None) self._token, self._exp = None, 0 def token(self): now = int(time.time()) if not self._token or now > self._exp - 60: head = _b64url(json.dumps({'alg': 'ES256', 'kid': self.key_id, 'typ': 'JWT'}).encode()) body = _b64url(json.dumps({'iss': self.issuer, 'iat': now, 'exp': now + 1200, 'aud': 'appstoreconnect-v1'}).encode()) r, s = decode_dss_signature(self.key.sign(f'{head}.{body}'.encode(), ec.ECDSA(hashes.SHA256()))) self._token = f'{head}.{body}.{_b64url(r.to_bytes(32, "big") + s.to_bytes(32, "big"))}' self._exp = now + 1200 return self._token def call(self, method, path, body=None, ok=(200, 201, 204)): url = path if path.startswith('http') else API + path req = urllib.request.Request(url, method=method, data=json.dumps(body).encode() if body is not None else None, headers={'Authorization': f'Bearer {self.token()}', 'Content-Type': 'application/json'}) try: with urllib.request.urlopen(req, timeout=120) as r: raw = r.read() return json.loads(raw) if raw else {} except urllib.error.HTTPError as e: if e.code in ok: return {} raise AscError(f'{method} {path} → HTTP {e.code}: {e.read().decode()[:1500]}') from None def get(self, path): return self.call('GET', path) def all(self, path): """Follow paging links; returns the concatenated data list.""" out, url = [], path while url: res = self.get(url) out += res.get('data', []) url = res.get('links', {}).get('next') return out def app(self): apps = self.get(f'/v1/apps?filter[bundleId]={BUNDLE_ID}')['data'] if not apps: raise AscError(f'no App Store Connect app for {BUNDLE_ID}') return apps[0]