Repository Public
1# =============================================================================2# SP BOUCHER | SOFTWARE & RESEARCH3# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# Project : SP ID & Card Vault7# File : scripts/asc.py8# Module : Scripts9# Repository : https://git.spboucher.ai/sp-id-card-vault10# Project Website : Not specified11# Created : 2026-12-0212# Last Modified : 2026-12-0213#14# Author : Simon-Pierre Boucher15# Position : Professor of Finance16# Institution : Université du Québec en Outaouais (UQO)17# Organization : SP Boucher18# Website : https://spboucher.ai19# Git : https://git.spboucher.ai20#21# Preferred Contact: contact@spboucher.ai22# Development : dev@spboucher.ai23# Support : support@spboucher.ai24# Security/Admin : admin@spboucher.ai25#26# Copyright (c) 202627# Simon-Pierre Boucher28# All rights reserved where applicable. This file is governed by the29# applicable project license, copyright notices and relevant law.30# Existing third-party rights and notices remain unaffected.31#32# License : None specified (no license file in this repository)33#34# Do not embed credentials, private keys, access tokens,35# certificates or confidential personal information.36#37# =============================================================================38# END OF SP BOUCHER SOURCE HEADER39# =============================================================================4041import json42import os43import sys44import time45import urllib.error46import urllib.request4748import jwt # PyJWT4950# Identifiers of the App Store Connect API key come from the environment51# (scripts/release.sh loads ~/.appstoreconnect/asc.env); none is kept in the repository.52KEY_ID = os.environ.get("ASC_KEY_ID", "")53ISSUER = os.environ.get("ASC_ISSUER_ID", "")54if not KEY_ID or not ISSUER:55 sys.exit("ASC_KEY_ID / ASC_ISSUER_ID missing (see ~/.appstoreconnect/asc.env)")56APP = os.environ.get("SPV_ASC_APP", "")57VERSION = os.environ.get("SPV_VERSION", "1.0.0")58BUNDLE = "ai.spboucher.idcardvault"59GROUP = "Test"60MODEL_APP = "6836172581" # SP Music iOS: its internal group holds the team's internal tester616263def token():64 key = open(os.path.expanduser(f"~/.appstoreconnect/private_keys/AuthKey_{KEY_ID}.p8")).read()65 now = int(time.time())66 return jwt.encode({"iss": ISSUER, "iat": now, "exp": now + 900, "aud": "appstoreconnect-v1"}, key,67 algorithm="ES256", headers={"kid": KEY_ID})686970def call(method, path, body=None):71 req = urllib.request.Request("https://api.appstoreconnect.apple.com" + path, method=method,72 data=json.dumps(body).encode() if body else None,73 headers={"Authorization": "Bearer " + token(), "Content-Type": "application/json"})74 try:75 with urllib.request.urlopen(req, timeout=40) as r:76 return r.status, json.loads(r.read() or b"{}")77 except urllib.error.HTTPError as e:78 return e.code, json.loads(e.read() or b"{}")798081def resolve_app():82 """The record's id: SPK_ASC_APP when set, otherwise looked up by bundle id."""83 global APP84 if APP:85 return APP86 s, j = call("GET", f"/v1/apps?filter[bundleId]={BUNDLE}&fields[apps]=name,bundleId,sku,primaryLocale")87 data = [a for a in j.get("data", []) if a["attributes"]["bundleId"] == BUNDLE]88 if not data:89 print(f"no App Store Connect record for {BUNDLE} (HTTP {s}) - create it with Scripts/portal/create-asc-record.js")90 sys.exit(1)91 APP = data[0]["id"]92 return APP939495def build(number=None):96 q = f"/v1/builds?filter[app]={APP}&filter[preReleaseVersion.version]={VERSION}&sort=-uploadedDate&limit=5"97 if number:98 q += f"&filter[version]={number}"99 s, j = call("GET", q)100 data = j.get("data", [])101 return data[0] if data else None102103104def groups():105 s, j = call("GET", f"/v1/apps/{APP}/betaGroups?fields[betaGroups]=name,isInternalGroup,hasAccessToAllBuilds&limit=50")106 return j.get("data", [])107108109def describe(b):110 a = b["attributes"]111 return f"{b['id']} {VERSION} ({a['version']}) {a['processingState']} encryption={a.get('usesNonExemptEncryption')} iOS min={a.get('minOsVersion')} expires={a.get('expirationDate')}"112113114def main():115 cmd = sys.argv[1] if len(sys.argv) > 1 else "build"116 number = sys.argv[2] if len(sys.argv) > 2 else None117 resolve_app()118 if cmd == "app":119 s, j = call("GET", f"/v1/apps/{APP}?fields[apps]=name,bundleId,sku,primaryLocale")120 print(APP, json.dumps(j.get("data", {}).get("attributes", {}), ensure_ascii=False))121 return 0122 if cmd == "build":123 b = build(number)124 print(describe(b) if b else f"no build {VERSION} {number or ''}")125 return 0 if b else 1126 if cmd == "wait":127 # the build shows up a few minutes after the upload, then goes from PROCESSING to VALID128 for _ in range(90):129 b = build(number)130 state = b["attributes"]["processingState"] if b else "not visible yet"131 print(time.strftime("%H:%M:%S"), state, flush=True)132 if state in ("VALID", "INVALID", "FAILED"):133 return 0 if state == "VALID" else 1134 time.sleep(20)135 return 1136 if cmd == "group":137 b = build(number)138 if not b:139 print("no build to attach")140 return 1141 internal = [g for g in groups() if g["attributes"]["isInternalGroup"]]142 if not internal:143 # First build of the app: the internal group is created, with the internal tester(s) of the model app's144 # internal group (people of the team; no external tester, no review).145 s, j = call("POST", "/v1/betaGroups", {"data": {"type": "betaGroups",146 "attributes": {"name": GROUP, "isInternalGroup": True, "hasAccessToAllBuilds": True},147 "relationships": {"app": {"data": {"type": "apps", "id": APP}}}}})148 if s >= 300:149 print("group creation refused:", s, json.dumps(j, ensure_ascii=False)[:600])150 return 1151 gid = j["data"]["id"]152 print(f"internal group « {GROUP} » created")153 s, j = call("GET", f"/v1/apps/{MODEL_APP}/betaGroups?fields[betaGroups]=isInternalGroup")154 model = next((g["id"] for g in j.get("data", []) if g["attributes"]["isInternalGroup"]), None)155 if model:156 s, j = call("GET", f"/v1/betaGroups/{model}/betaTesters?limit=50")157 for t in j.get("data", []):158 a = t["attributes"]159 s2, j2 = call("POST", "/v1/betaTesters", {"data": {"type": "betaTesters",160 "attributes": {"email": a["email"], "firstName": a.get("firstName"), "lastName": a.get("lastName")},161 "relationships": {"betaGroups": {"data": [{"type": "betaGroups", "id": gid}]}}}})162 print("internal tester added" if s2 < 300 else f"tester refused: {s2} {json.dumps(j2, ensure_ascii=False)[:300]}")163 internal = [g for g in groups() if g["attributes"]["isInternalGroup"]]164 for g in internal:165 a = g["attributes"]166 if a.get("hasAccessToAllBuilds"):167 print(f"internal group « {a['name']} »: access to all builds, nothing to attach")168 continue169 s, j = call("POST", f"/v1/betaGroups/{g['id']}/relationships/builds", {"data": [{"type": "builds", "id": b["id"]}]})170 print(f"internal group « {a['name']} »: build attached" if s < 300 else f"attachment refused: {s} {json.dumps(j, ensure_ascii=False)[:400]}")171 return 0172 if cmd == "status":173 b = build(number)174 if not b:175 print(f"no build {VERSION} {number or ''}")176 return 1177 print(describe(b))178 s, j = call("GET", f"/v1/builds/{b['id']}/buildBetaDetail")179 d = j.get("data", {}).get("attributes", {})180 print("internal testing:", d.get("internalBuildState"), "| external testing:", d.get("externalBuildState"))181 s, j = call("GET", f"/v1/builds/{b['id']}/betaAppReviewSubmission")182 print("beta review:", (j.get("data") or {}).get("attributes", {}).get("betaReviewState", "no submission"))183 for g in groups():184 a = g["attributes"]185 s, j = call("GET", f"/v1/betaGroups/{g['id']}/builds?limit=200&fields[builds]=version")186 has = any(x["id"] == b["id"] for x in j.get("data", []))187 s, t = call("GET", f"/v1/betaGroups/{g['id']}/betaTesters?limit=50")188 print(f"group « {a['name']} » ({'internal' if a['isInternalGroup'] else 'external'}): "189 f"{'all builds' if a.get('hasAccessToAllBuilds') else ('has this build' if has else 'does not have this build')}, {len(t.get('data', []))} tester(s)")190 return 0191 print("usage: asc.py app | build [number] | wait [number] | group [number] | status [number]")192 return 2193194195if __name__ == "__main__":196 sys.exit(main())197