NarratifAI / src /apple_iap.py
Consulawtech's picture
Claude Opus 5.5 (1M context)
Apple in-app purchase: /credits/apple and /apple/notifications
07f9ba9
Raw History Blame Contribute Delete
4.25 kB
"""Verify App Store (StoreKit 2) signed data without any Apple API key.
StoreKit 2 transactions and App Store Server Notifications are JWS strings
signed by Apple. The header carries the certificate chain (x5c): leaf,
intermediate, root. A transaction is genuine when
1. the root certificate is exactly Apple Root CA - G3 (pinned by SHA-256),
2. the intermediate is signed by that root and the leaf by the intermediate,
and both carry Apple's marker extensions,
3. the JWS signature (ES256) verifies with the leaf's public key.
https://developer.apple.com/documentation/appstoreserverapi/jwstransaction
"""
from __future__ import annotations
import base64
import hashlib
import json
import uuid
from datetime import datetime, timezone
from cryptography import x509
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.asymmetric import ec
from cryptography.hazmat.primitives.asymmetric.utils import encode_dss_signature
# SHA-256 of Apple Root CA - G3 (DER), from https://www.apple.com/certificateauthority/
APPLE_ROOT_G3_SHA256 = "63343abfb89a6a03ebb57e9b3f5fa7be7c4f5c756f3017b3a8c488c3653e9179"
# Marker extensions Apple puts on its App Store signing certificates.
_OID_INTERMEDIATE = x509.ObjectIdentifier("1.2.840.113635.100.6.2.1")
_OID_LEAF = x509.ObjectIdentifier("1.2.840.113635.100.6.11.1")
class AppleJWSError(Exception):
pass
def _b64url(data: str) -> bytes:
return base64.urlsafe_b64decode(data + "=" * (-len(data) % 4))
def _has_ext(cert: x509.Certificate, oid: x509.ObjectIdentifier) -> bool:
try:
cert.extensions.get_extension_for_oid(oid)
return True
except x509.ExtensionNotFound:
return False
def verify_jws(jws: str, root_sha256: str = APPLE_ROOT_G3_SHA256, now: datetime | None = None) -> dict:
"""Return the decoded payload of an Apple-signed JWS, or raise AppleJWSError."""
try:
header_b64, payload_b64, sig_b64 = jws.split(".")
header = json.loads(_b64url(header_b64))
except Exception:
raise AppleJWSError("not a JWS")
if header.get("alg") != "ES256":
raise AppleJWSError("unexpected algorithm")
chain = header.get("x5c") or []
if len(chain) != 3:
raise AppleJWSError("certificate chain must have 3 certificates")
try:
leaf, inter, root = (x509.load_der_x509_certificate(base64.b64decode(c)) for c in chain)
except Exception:
raise AppleJWSError("bad certificate in chain")
if hashlib.sha256(root.public_bytes(_der())).hexdigest() != root_sha256:
raise AppleJWSError("root certificate is not Apple Root CA - G3")
try:
inter.verify_directly_issued_by(root)
leaf.verify_directly_issued_by(inter)
except Exception:
raise AppleJWSError("certificate chain does not verify")
if not (_has_ext(inter, _OID_INTERMEDIATE) and _has_ext(leaf, _OID_LEAF)):
raise AppleJWSError("certificates are not App Store signing certificates")
at = now or datetime.now(timezone.utc)
for c in (leaf, inter, root):
if not (c.not_valid_before_utc <= at <= c.not_valid_after_utc):
raise AppleJWSError("certificate expired or not yet valid")
raw = _b64url(sig_b64)
if len(raw) != 64:
raise AppleJWSError("bad signature length")
der_sig = encode_dss_signature(int.from_bytes(raw[:32], "big"), int.from_bytes(raw[32:], "big"))
pub = leaf.public_key()
if not isinstance(pub, ec.EllipticCurvePublicKey):
raise AppleJWSError("leaf key is not EC")
try:
pub.verify(der_sig, f"{header_b64}.{payload_b64}".encode(), ec.ECDSA(hashes.SHA256()))
except Exception:
raise AppleJWSError("signature does not verify")
try:
return json.loads(_b64url(payload_b64))
except Exception:
raise AppleJWSError("payload is not JSON")
def _der():
from cryptography.hazmat.primitives.serialization import Encoding
return Encoding.DER
def account_token(firebase_uid: str) -> str:
"""The appAccountToken the app attaches to purchases: a UUID derived from
the Firebase uid, so a transaction can only be redeemed by its buyer."""
return str(uuid.uuid5(uuid.NAMESPACE_URL, f"narratifai:{firebase_uid}"))