waiting for ios review

This commit is contained in:
sagiferi
2026-10-25 07:11:03 +01:00
parent b33d1543fc
commit b84eef0b53
42 changed files with 1687 additions and 155 deletions
+77
View File
@@ -0,0 +1,77 @@
"""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]
+178
View File
@@ -0,0 +1,178 @@
#!/usr/bin/env python3
"""One-time App Store signing setup through the App Store Connect API.
Why: Apple's cloud-managed distribution signing writes the certificate name
into each binary's designated requirement in Unicode-decomposed form
("Sági"), while the certificate itself holds the composed form ("Sági").
The requirement then never matches and App Store Connect rejects the upload
(ITMS-90035). Signing locally with our own distribution certificate and an
explicit, ASCII-only requirement avoids that (see scripts/ios_release.sh).
This script:
1. checks the app record and bundle ID exist,
2. creates a local key + Apple Distribution certificate (reuses it if present),
3. creates an App Store provisioning profile for it,
4. puts key + certificate into a dedicated keychain (not the login keychain).
Secrets stay outside the repo in ~/.appstoreconnect/skycontour/.
Usage: python3 scripts/asc_signing_setup.py --key-id KEY --issuer ISSUER
"""
import argparse
import base64
import json
import os
import secrets
import subprocess
import sys
import time
import urllib.error
import urllib.request
from pathlib import Path
from cryptography import x509
from cryptography.hazmat.primitives import hashes, serialization
from cryptography.hazmat.primitives.asymmetric import ec, rsa
from cryptography.hazmat.primitives.asymmetric.utils import decode_dss_signature
from cryptography.x509.oid import NameOID
BUNDLE_ID = 'com.sagifer.skycontour.ios'
TEAM_ID = '8EQZ487TY9'
API = 'https://api.appstoreconnect.apple.com/v1'
HOME = Path.home() / '.appstoreconnect'
OUT = HOME / 'skycontour'
KEYCHAIN = Path.home() / 'Library/Keychains/skycontour-signing.keychain-db'
def b64url(b):
return base64.urlsafe_b64encode(b).rstrip(b'=').decode()
def jwt(key_id, issuer):
key = serialization.load_pem_private_key((HOME / f'private_keys/AuthKey_{key_id}.p8').read_bytes(), None)
now = int(time.time())
head = b64url(json.dumps({'alg': 'ES256', 'kid': key_id, 'typ': 'JWT'}).encode())
body = b64url(json.dumps({'iss': issuer, 'iat': now, 'exp': now + 900, 'aud': 'appstoreconnect-v1'}).encode())
r, s = decode_dss_signature(key.sign(f'{head}.{body}'.encode(), ec.ECDSA(hashes.SHA256())))
return f'{head}.{body}.{b64url(r.to_bytes(32, "big") + s.to_bytes(32, "big"))}'
class Api:
def __init__(self, key_id, issuer):
self.token = jwt(key_id, issuer)
def call(self, method, path, body=None):
req = urllib.request.Request(API + path, method=method, data=json.dumps(body).encode() if body else None,
headers={'Authorization': f'Bearer {self.token}', 'Content-Type': 'application/json'})
try:
with urllib.request.urlopen(req, timeout=60) as r:
return json.loads(r.read() or b'{}')
except urllib.error.HTTPError as e:
sys.exit(f'{method} {path} → HTTP {e.code}: {e.read().decode()[:600]}')
def sh(*args, check=True):
return subprocess.run(args, check=check, capture_output=True, text=True)
def main():
ap = argparse.ArgumentParser()
ap.add_argument('--key-id', required=True)
ap.add_argument('--issuer', required=True)
a = ap.parse_args()
OUT.mkdir(parents=True, exist_ok=True)
os.chmod(OUT, 0o700)
api = Api(a.key_id, a.issuer)
# 1. App record + bundle ID
bid = [b for b in api.call('GET', f'/bundleIds?filter[identifier]={BUNDLE_ID}&limit=50')['data']
if b['attributes']['identifier'] == BUNDLE_ID]
if not bid:
sys.exit(f'Bundle ID {BUNDLE_ID} is not registered for this team')
bundle_id = bid[0]['id']
apps = api.call('GET', f'/apps?filter[bundleId]={BUNDLE_ID}')['data']
print('app record:', apps[0]['attributes']['name'] if apps else 'MISSING (create it in App Store Connect)')
# 2. Distribution certificate (reuse ours if the key is still here)
key_path, cert_path, meta_path = OUT / 'distribution.key.pem', OUT / 'distribution.cer', OUT / 'meta.json'
meta = json.loads(meta_path.read_text()) if meta_path.exists() else {}
if key_path.exists() and cert_path.exists() and meta.get('certificateId'):
print('reusing local distribution certificate', meta['certificateId'])
key = serialization.load_pem_private_key(key_path.read_bytes(), None)
cert = x509.load_der_x509_certificate(cert_path.read_bytes())
else:
key = rsa.generate_private_key(public_exponent=65537, key_size=2048)
key_path.write_bytes(key.private_bytes(serialization.Encoding.PEM, serialization.PrivateFormat.PKCS8,
serialization.NoEncryption()))
os.chmod(key_path, 0o600)
csr = (x509.CertificateSigningRequestBuilder()
.subject_name(x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, 'SkyContour distribution')]))
.sign(key, hashes.SHA256()))
res = api.call('POST', '/certificates', {'data': {'type': 'certificates', 'attributes': {
'certificateType': 'DISTRIBUTION', 'csrContent': csr.public_bytes(serialization.Encoding.PEM).decode()}}})
der = base64.b64decode(res['data']['attributes']['certificateContent'])
cert_path.write_bytes(der)
cert = x509.load_der_x509_certificate(der)
meta['certificateId'] = res['data']['id']
print('created distribution certificate', meta['certificateId'], 'expires', cert.not_valid_after_utc.date())
meta['certificateSha1'] = cert.fingerprint(hashes.SHA1()).hex().upper()
meta_path.write_text(json.dumps(meta, indent=2))
# 3. App Store profile bound to this certificate (reused while it exists)
prof = OUT / 'appstore.mobileprovision'
if prof.exists() and meta.get('profileId'):
print('reusing App Store profile', meta['profileId'])
else:
res = api.call('POST', '/profiles', {'data': {'type': 'profiles',
'attributes': {'name': f'SkyContour App Store {time.strftime("%Y%m%d-%H%M%S")}', 'profileType': 'IOS_APP_STORE'},
'relationships': {'bundleId': {'data': {'type': 'bundleIds', 'id': bundle_id}},
'certificates': {'data': [{'type': 'certificates', 'id': meta['certificateId']}]}}}})
prof.write_bytes(base64.b64decode(res['data']['attributes']['profileContent']))
meta['profileId'] = res['data']['id']
meta_path.write_text(json.dumps(meta, indent=2))
print('created App Store profile', res['data']['attributes']['name'])
# 4. Dedicated keychain with key + certificate (codesign can use it without prompts)
pw_path = OUT / 'keychain.password'
if not pw_path.exists():
pw_path.write_text(secrets.token_urlsafe(24))
os.chmod(pw_path, 0o600)
pw = pw_path.read_text().strip()
if not KEYCHAIN.exists():
sh('security', 'create-keychain', '-p', pw, str(KEYCHAIN))
sh('security', 'unlock-keychain', '-p', pw, str(KEYCHAIN))
sh('security', 'set-keychain-settings', str(KEYCHAIN)) # no auto-lock
# Key and certificate separately: macOS `security` cannot read the modern
# (AES/PBKDF2) PKCS#12 files that Python/OpenSSL 3 write by default.
(OUT / 'distribution.p12').unlink(missing_ok=True) # left over by an older version
if not sh('security', 'find-identity', '-v', '-p', 'codesigning', str(KEYCHAIN)).stdout.count(')') :
# `security` wants the traditional "BEGIN RSA PRIVATE KEY" form, not PKCS#8.
legacy = OUT / 'distribution.rsa.pem'
legacy.write_bytes(key.private_bytes(serialization.Encoding.PEM, serialization.PrivateFormat.TraditionalOpenSSL,
serialization.NoEncryption()))
os.chmod(legacy, 0o600)
try:
for path, kind, fmt in ((legacy, 'priv', 'openssl'), (cert_path, 'cert', 'x509')):
r = sh('security', 'import', str(path), '-k', str(KEYCHAIN), '-t', kind, '-f', fmt,
'-T', '/usr/bin/codesign', check=False)
if r.returncode != 0 and 'already exists' not in r.stderr:
sys.exit(f'keychain import of {path.name} failed: {r.stderr.strip()}')
finally:
legacy.unlink(missing_ok=True)
r = sh('security', 'set-key-partition-list', '-S', 'apple-tool:,apple:,codesign:', '-s', '-k', pw,
str(KEYCHAIN), check=False)
if r.returncode != 0:
sys.exit('set-key-partition-list failed: ' + r.stderr.strip())
listed = sh('security', 'list-keychains', '-d', 'user').stdout.split()
listed = [k.strip('"') for k in listed]
if str(KEYCHAIN) not in listed:
sh('security', 'list-keychains', '-d', 'user', '-s', *listed, str(KEYCHAIN))
ident = sh('security', 'find-identity', '-v', '-p', 'codesigning', str(KEYCHAIN)).stdout.strip()
print(ident)
if meta['certificateSha1'] not in ident:
sys.exit('the distribution identity is not usable in the signing keychain')
print('signing identity SHA1:', meta['certificateSha1'], '| team', TEAM_ID)
if __name__ == '__main__':
main()
+1 -1
View File
@@ -23,5 +23,5 @@ echo "==> Done. assets/web/ contents:"
ls -la assets/web
echo
echo "Flutter will serve this at http://localhost:8080 via InAppLocalhostServer."
echo "Flutter will serve this at http://localhost:47391 (lib/local_server.dart)."
echo "Remember to run 'flutter pub get' if pubspec assets changed."
+1 -1
View File
@@ -51,4 +51,4 @@ echo "==> Installing"
xcrun devicectl device install app --device "$DEVICE" "$APP"
echo "==> Launching (first time: trust the developer on the phone, see README)"
xcrun devicectl device process launch --device "$DEVICE" com.sagifer.skycontour || true
xcrun devicectl device process launch --device "$DEVICE" com.sagifer.skycontour.ios || true
+84
View File
@@ -0,0 +1,84 @@
#!/usr/bin/env bash
# Build the App Store IPA, re-sign it locally and validate (or upload) it.
#
# Why the re-sign: Apple's cloud-managed distribution signing stores the
# certificate name ("Apple Distribution: Ferenc Sági (8EQZ487TY9)") in each
# binary's designated requirement in decomposed Unicode ("Sági"); the
# certificate holds the composed form, so the requirement never matches and
# App Store Connect rejects the build (ITMS-90035). We sign with our own
# distribution certificate (scripts/asc_signing_setup.py) and an explicit
# ASCII-only requirement keyed on the team ID.
#
# Usage: ./scripts/ios_release.sh [--upload]
# Needs: ~/.appstoreconnect/private_keys/AuthKey_<KEY>.p8 and the setup above.
set -euo pipefail
KEY_ID="${ASC_KEY_ID:-HGF8KY67BH}"
ISSUER="${ASC_ISSUER:-69a6de8c-48b0-47e3-e053-5b8c7c11a4d1}"
TEAM_ID="8EQZ487TY9"
SIGN_DIR="$HOME/.appstoreconnect/skycontour"
KEYCHAIN="$HOME/Library/Keychains/skycontour-signing.keychain-db"
ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
cd "$ROOT"
# Non-login shells may lack flutter on PATH: fall back to the SDK recorded by Android tooling.
if ! command -v flutter >/dev/null; then
FLUTTER_SDK="$(sed -n 's/^flutter.sdk=//p' android/local.properties 2>/dev/null)"
[ -x "$FLUTTER_SDK/bin/flutter" ] && export PATH="$FLUTTER_SDK/bin:$PATH"
fi
[ -f "$SIGN_DIR/meta.json" ] || { echo "Run scripts/asc_signing_setup.py first." >&2; exit 1; }
SHA1="$(python3 -I -c 'import json,sys; print(json.load(open(sys.argv[1]))["certificateSha1"])' "$SIGN_DIR/meta.json")"
PROFILE="$SIGN_DIR/appstore.mobileprovision"
security unlock-keychain -p "$(cat "$SIGN_DIR/keychain.password")" "$KEYCHAIN"
echo "==> Web bundle + App Store IPA"
./scripts/build_web.sh > /dev/null
flutter build ipa --release
WORK="$(mktemp -d)"
trap 'rm -rf "$WORK"' EXIT
( cd "$WORK" && unzip -q "$ROOT/build/ios/ipa/SkyContour.ipa" )
APP="$WORK/Payload/Runner.app"
# Same entitlements as Xcode produced (application-identifier, team, beta reports).
codesign -d --entitlements :- "$APP" > "$WORK/entitlements.plist" 2>/dev/null
cp "$PROFILE" "$APP/embedded.mobileprovision"
requirement() {
echo "designated => anchor apple generic and identifier \"$1\" and certificate leaf[subject.OU] = \"$TEAM_ID\" and certificate 1[field.1.2.840.113635.100.6.2.1] /* exists */"
}
sign() { # path [entitlements]
local id
id="$(codesign -dv "$1" 2>&1 | sed -n 's/^Identifier=//p')"
codesign --force --sign "$SHA1" --keychain "$KEYCHAIN" --timestamp=none \
-r="$(requirement "$id")" ${2:+--entitlements "$2"} "$1"
}
echo "==> Re-signing with the local distribution certificate"
find "$APP/Frameworks" -maxdepth 1 \( -name '*.framework' -o -name '*.dylib' \) -print0 |
while IFS= read -r -d '' f; do sign "$f"; done
sign "$APP" "$WORK/entitlements.plist"
# --verify also checks each binary against its designated requirement (the ITMS-90035 check).
for f in "$APP"/Frameworks/*.framework "$APP"; do
if ! out="$(codesign --verify --strict --verbose=2 "$f" 2>&1)" || grep -q 'does not satisfy' <<<"$out"; then
echo "signature check failed: $out" >&2
exit 1
fi
done
codesign --verify --strict --deep "$APP"
OUT="$ROOT/build/ios/ipa/SkyContour-appstore.ipa"
rm -f "$OUT"
( cd "$WORK" && zip -qry "$OUT" Payload )
echo "==> $OUT"
echo "==> Validating with App Store Connect"
xcrun altool --validate-app -f "$OUT" -t ios --apiKey "$KEY_ID" --apiIssuer "$ISSUER"
if [ "${1:-}" = "--upload" ]; then
echo "==> Uploading"
xcrun altool --upload-app -f "$OUT" -t ios --apiKey "$KEY_ID" --apiIssuer "$ISSUER"
fi