Modern Apps git

← xtool.git

dist: add xtool dist upload and submit for App Store Connect

Commit
8c0deb210b4b48bd748fd40bfeaad64f99d0bd0f
Author
Vayun Mathur <[email protected]>
When
2026-11-18 15:58 UTC (17 days ago)
Parents
8ab0a62
upload creates a buildUpload + buildUploadFile, PUTs each signed chunk, and marks both uploaded; submit ensures the app-store version, upserts the whatsNew localization, attaches the processed build, and submits a review submission. Output contract BUILD_ID:/BUILD_STATE: and SUBMISSION_ID:/SUBMISSION_STATE: for the Modern-Apps release pipeline. Auth from XTOOL_ASC_KEY_ID/ISSUER_ID/KEY_PATH or xtool auth; XTOOL_ASC_BASE_URL overrides the API host for tests. Verified end-to-end against a local stub ASC server with the real FindFamily IPA.

Diff

Sources/XToolSupport/AppStoreConnect.swift
diff --git a/Sources/XToolSupport/AppStoreConnect.swift b/Sources/XToolSupport/AppStoreConnect.swiftnew file mode 100644index 0000000..b5fd341--- /dev/null+++ b/Sources/XToolSupport/AppStoreConnect.swift@@ -0,0 +1,462 @@+import Foundation+#if canImport(FoundationNetworking)+import FoundationNetworking+#endif+import Crypto+import XKit+import XUtils+import Subprocess++/// Resolves the App Store Connect API key used by `xtool dist` and by+/// app-store distribution signing.+///+/// Precedence: `XTOOL_ASC_KEY_ID` + `XTOOL_ASC_ISSUER_ID` ++/// `XTOOL_ASC_KEY_PATH` (the env contract used by the Modern-Apps release+/// pipeline), then the key saved by `xtool auth`.+func resolveASCKey() throws -> ASCKey {+    let env = ProcessInfo.processInfo.environment+    if let id = env["XTOOL_ASC_KEY_ID"], let issuer = env["XTOOL_ASC_ISSUER_ID"],+       let path = env["XTOOL_ASC_KEY_PATH"] {+        let pem = try String(contentsOfFile: path, encoding: .utf8)+        return ASCKey(id: id, issuerID: issuer, pem: pem)+    }+    if let token = try AuthToken.savedIfPresent(), case .appStoreConnect(let asc) = token {+        return ASCKey(id: asc.id, issuerID: asc.issuerID, pem: asc.pem)+    }+    throw Console.Error("""+    No App Store Connect API key available. Either set XTOOL_ASC_KEY_ID, \+    XTOOL_ASC_ISSUER_ID and XTOOL_ASC_KEY_PATH, or log in with `xtool auth`.+    """)+}++/// Minimal JSON value used to talk to App Store Connect without depending+/// on the generated OpenAPI types (which only cover provisioning).+enum ASCJSON: Sendable {+    case object([String: ASCJSON])+    case array([ASCJSON])+    case string(String)+    case number(Double)+    case bool(Bool)+    case null++    init(parsing data: Data) throws {+        let raw = try JSONSerialization.jsonObject(with: data)+        self = try ASCJSON(raw: raw)+    }++    init(raw: Any) throws {+        switch raw {+        case let dict as [String: Any]:+            self = .object(try dict.mapValues { try ASCJSON(raw: $0) })+        case let array as [Any]:+            self = .array(try array.map { try ASCJSON(raw: $0) })+        case let string as String:+            self = .string(string)+        case let number as NSNumber:+            // JSONSerialization turns booleans into NSNumber too; the+            // objCType distinguishes them (char-backed for booleans).+            if String(cString: number.objCType) == "c" {+                self = .bool(number.boolValue)+            } else {+                self = .number(number.doubleValue)+            }+        case is NSNull:+            self = .null+        default:+            throw Console.Error("Unexpected JSON value: \(type(of: raw))")+        }+    }++    func serialize() throws -> Data {+        try JSONSerialization.data(withJSONObject: rawObject, options: [.sortedKeys])+    }++    var rawObject: Any {+        switch self {+        case .object(let dict): dict.mapValues { $0.rawObject }+        case .array(let array): array.map { $0.rawObject }+        case .string(let string): string+        case .number(let number): number+        case .bool(let bool): bool+        case .null: NSNull()+        }+    }++    subscript(key: String) -> ASCJSON? {+        guard case .object(let dict) = self else { return nil }+        return dict[key]+    }++    var stringValue: String? {+        guard case .string(let string) = self else { return nil }+        return string+    }++    var boolValue: Bool? {+        guard case .bool(let bool) = self else { return nil }+        return bool+    }++    var arrayValue: [ASCJSON]? {+        guard case .array(let array) = self else { return nil }+        return array+    }++    var objectValue: [String: ASCJSON]? {+        guard case .object(let dict) = self else { return nil }+        return dict+    }+}++/// Thin App Store Connect REST client (build uploads + review submission).+///+/// The base URL can be overridden with `XTOOL_ASC_BASE_URL`, which the tests+/// use to run against a local stub server.+struct AppStoreConnectClient: Sendable {+    var key: ASCKey+    var baseURL: URL++    init(key: ASCKey) {+        self.key = key+        let override = ProcessInfo.processInfo.environment["XTOOL_ASC_BASE_URL"]+        self.baseURL = URL(string: override ?? "https://api.appstoreconnect.apple.com")!+    }++    func request(+        method: String,+        path: String,+        query: [String: String] = [:],+        body: ASCJSON? = nil+    ) async throws -> ASCJSON {+        var components = URLComponents(url: baseURL.appendingPathComponent(path), resolvingAgainstBaseURL: false)!+        if !query.isEmpty {+            components.queryItems = query.map { URLQueryItem(name: $0.key, value: $0.value) }.sorted { $0.name < $1.name }+        }+        var request = URLRequest(url: components.url!)+        request.httpMethod = method+        request.setValue("Bearer \(try await key.makeJWT())", forHTTPHeaderField: "Authorization")+        if let body {+            request.httpBody = try body.serialize()+            request.setValue("application/json", forHTTPHeaderField: "Content-Type")+        }+        let (data, response) = try await URLSession.shared.data(for: request)+        guard let http = response as? HTTPURLResponse else {+            throw Console.Error("App Store Connect: no HTTP response for \(method) \(path)")+        }+        guard (200..<300).contains(http.statusCode) else {+            throw Console.Error(+                "App Store Connect \(method) \(path) failed: HTTP \(http.statusCode)\n"+                    + String(decoding: data, as: UTF8.self)+            )+        }+        if data.isEmpty { return .object([:]) }+        return try ASCJSON(parsing: data)+    }++    // MARK: - Build upload++    struct IPAMetadata: Sendable {+        var bundleID: String+        var version: String+        var buildNumber: String+    }++    /// Reads CFBundleIdentifier / CFBundleShortVersionString / CFBundleVersion+    /// from the `.app` inside an `.ipa` (via `unzip`, available on builders).+    static func ipaMetadata(at ipa: URL) async throws -> IPAMetadata {+        let listing = try await Subprocess.run(+            .name("unzip"),+            arguments: ["-Z1", ipa.path],+            output: .string(limit: .max)+        ).checkSuccess().standardOutput++        guard let plistPath = listing.split(separator: "\n").map(String.init)+            .first(where: { $0.hasPrefix("Payload/") && $0.hasSuffix(".app/Info.plist") }) else {+            throw Console.Error("No Payload/*.app/Info.plist found in '\(ipa.path)'")+        }+        let plistData = try await Subprocess.run(+            .name("unzip"),+            arguments: ["-p", ipa.path, plistPath],+            output: .data(limit: .max)+        ).checkSuccess().standardOutput++        let plist = try PropertyListSerialization.propertyList(from: plistData, format: nil)+        guard let dict = plist as? [String: Any],+              let bundleID = dict["CFBundleIdentifier"] as? String,+              let version = dict["CFBundleShortVersionString"] as? String,+              let buildNumber = dict["CFBundleVersion"] as? String else {+            throw Console.Error("Info.plist in '\(ipa.path)' is missing bundle id / version keys")+        }+        return IPAMetadata(bundleID: bundleID, version: version, buildNumber: buildNumber)+    }++    struct Checksums: Sendable {+        var md5: String+        var sha256: String+    }++    static func checksums(of file: URL) throws -> Checksums {+        let handle = try FileHandle(forReadingFrom: file)+        defer { try? handle.close() }+        var md5 = Insecure.MD5()+        var sha256 = SHA256()+        while let chunk = try handle.read(upToCount: 1 << 20), !chunk.isEmpty {+            md5.update(data: chunk)+            sha256.update(data: chunk)+        }+        func hex(_ digest: some Sequence<UInt8>) -> String {+            digest.map { String(format: "%02x", $0) }.joined()+        }+        return Checksums(md5: hex(md5.finalize()), sha256: hex(sha256.finalize()))+    }++    struct UploadResult: Sendable {+        var buildID: String+        var state: String+    }++    /// Uploads an `.ipa` using the App Store Connect build-uploads API:+    /// create buildUpload -> create buildUploadFile -> PUT each signed chunk+    /// -> mark both uploaded. Returns the resulting build id when Apple has+    /// linked one, otherwise the build-upload id.+    func uploadIPA(at ipa: URL) async throws -> UploadResult {+        let metadata = try await Self.ipaMetadata(at: ipa)+        let fileSize = try FileManager.default.attributesOfItem(atPath: ipa.path)[.size] as? Int ?? 0+        let checksums = try Self.checksums(of: ipa)++        guard let appID = try await findAppID(bundleID: metadata.bundleID) else {+            throw Console.Error("No App Store Connect app found for bundle id '\(metadata.bundleID)'")+        }++        let upload = try await request(method: "POST", path: "/v1/buildUploads", body: .object([+            "data": .object([+                "type": .string("buildUploads"),+                "attributes": .object([+                    "cfBundleIdentifier": .string(metadata.bundleID),+                    "cfBundleShortVersionString": .string(metadata.version),+                    "cfBundleVersion": .string(metadata.buildNumber),+                    "platform": .string("IOS"),+                ]),+                "relationships": .object([+                    "app": .object(["data": .object(["type": .string("apps"), "id": .string(appID)])])+                ]),+            ]),+        ]))+        guard let uploadID = upload["data"]?["id"]?.stringValue else {+            throw Console.Error("buildUploads create returned no id: \(upload)")+        }++        let file = try await request(method: "POST", path: "/v1/buildUploadFiles", body: .object([+            "data": .object([+                "type": .string("buildUploadFiles"),+                "attributes": .object([+                    "fileName": .string(ipa.lastPathComponent),+                    "fileSize": .number(Double(fileSize)),+                    "uti": .string("com.apple.ipa"),+                    "sourceFileChecksums": .object([+                        "file": .object(["algorithm": .string("MD5"), "hash": .string(checksums.md5)]),+                        "composite": .object(["algorithm": .string("MD5"), "hash": .string(checksums.md5)]),+                    ]),+                ]),+                "relationships": .object([+                    "buildUpload": .object(["data": .object(["type": .string("buildUploads"), "id": .string(uploadID)])])+                ]),+            ]),+        ]))+        guard let fileID = file["data"]?["id"]?.stringValue,+              let operations = file["data"]?["attributes"]?["uploadOperations"]?.arrayValue else {+            throw Console.Error("buildUploadFiles create returned no upload operations: \(file)")+        }++        let data = try Data(contentsOf: ipa)+        for operation in operations {+            try await uploadChunk(operation: operation, data: data)+        }++        _ = try await request(method: "PATCH", path: "/v1/buildUploadFiles/\(fileID)", body: .object([+            "data": .object([+                "type": .string("buildUploadFiles"),+                "id": .string(fileID),+                "attributes": .object([+                    "uploaded": .bool(true),+                    "sourceFileChecksums": .object([+                        "file": .object(["algorithm": .string("MD5"), "hash": .string(checksums.md5)]),+                        "composite": .object(["algorithm": .string("MD5"), "hash": .string(checksums.md5)]),+                    ]),+                ]),+            ]),+        ]))+        let finished = try await request(method: "PATCH", path: "/v1/buildUploads/\(uploadID)", body: .object([+            "data": .object([+                "type": .string("buildUploads"),+                "id": .string(uploadID),+                "attributes": .object(["uploaded": .bool(true)]),+            ]),+        ]))++        let state = finished["data"]?["attributes"]?["state"]?.stringValue+            ?? upload["data"]?["attributes"]?["state"]?.stringValue ?? "UNKNOWN"+        // Apple links a Build once processing starts; surface it when present.+        let linkedBuild = finished["included"]?.arrayValue?+            .first { $0["type"]?.stringValue == "builds" }?["id"]?.stringValue+        return UploadResult(buildID: linkedBuild ?? uploadID, state: state)+    }++    private func uploadChunk(operation: ASCJSON, data: Data) async throws {+        guard let urlString = operation["url"]?.stringValue, let url = URL(string: urlString),+              let method = operation["method"]?.stringValue,+              let offsetJSON = operation["offset"], let lengthJSON = operation["length"],+              case .number(let offset) = offsetJSON, case .number(let length) = lengthJSON else {+            throw Console.Error("Malformed upload operation: \(operation)")+        }+        var request = URLRequest(url: url)+        request.httpMethod = method+        for header in operation["requestHeaders"]?.arrayValue ?? [] {+            if let name = header["name"]?.stringValue, let value = header["value"]?.stringValue {+                request.setValue(value, forHTTPHeaderField: name)+            }+        }+        request.httpBody = data.subdata(in: Int(offset)..<Int(offset + length))+        let (_, response) = try await URLSession.shared.data(for: request)+        guard let http = response as? HTTPURLResponse, (200..<300).contains(http.statusCode) else {+            throw Console.Error("Chunk upload failed: \(String(describing: response))")+        }+    }++    // MARK: - Review submission++    func findAppID(bundleID: String) async throws -> String? {+        let response = try await request(+            method: "GET", path: "/v1/apps",+            query: ["filter[bundleId]": bundleID, "fields[apps]": "bundleId"]+        )+        return response["data"]?.arrayValue?+            .first { $0["attributes"]?["bundleId"]?.stringValue == bundleID }?["id"]?.stringValue+    }++    struct SubmissionResult: Sendable {+        var submissionID: String+        var state: String+    }++    /// Ensures an App Store version exists with the given `whatsNew`, attaches+    /// the uploaded build, and submits it for review.+    func submitForReview(+        bundleID: String,+        version: String,+        buildNumber: String,+        whatsNew: String,+        locale: String+    ) async throws -> SubmissionResult {+        guard let appID = try await findAppID(bundleID: bundleID) else {+            throw Console.Error("No App Store Connect app found for bundle id '\(bundleID)'")+        }++        let versionID = try await ensureVersion(appID: appID, version: version)+        try await upsertWhatsNew(versionID: versionID, whatsNew: whatsNew, locale: locale)++        guard let buildID = try await findBuild(appID: appID, buildNumber: buildNumber, version: version) else {+            throw Console.Error("No processed build '\(buildNumber)' (\(version)) found for app \(appID) yet")+        }+        _ = try await request(method: "PATCH", path: "/v1/appStoreVersions/\(versionID)/relationships/build", body: .object([+            "data": .object(["type": .string("builds"), "id": .string(buildID)]),+        ]))++        let submission = try await request(method: "POST", path: "/v1/reviewSubmissions", body: .object([+            "data": .object([+                "type": .string("reviewSubmissions"),+                "attributes": .object(["platform": .string("IOS"), "submitted": .bool(false)]),+                "relationships": .object([+                    "app": .object(["data": .object(["type": .string("apps"), "id": .string(appID)])])+                ]),+            ]),+        ]))+        guard let submissionID = submission["data"]?["id"]?.stringValue else {+            throw Console.Error("reviewSubmissions create returned no id: \(submission)")+        }+        _ = try await request(method: "POST", path: "/v1/reviewSubmissionItems", body: .object([+            "data": .object([+                "type": .string("reviewSubmissionItems"),+                "relationships": .object([+                    "reviewSubmission": .object(["data": .object(["type": .string("reviewSubmissions"), "id": .string(submissionID)])]),+                    "appStoreVersion": .object(["data": .object(["type": .string("appStoreVersions"), "id": .string(versionID)])]),+                ]),+            ]),+        ]))+        let submitted = try await request(method: "PATCH", path: "/v1/reviewSubmissions/\(submissionID)", body: .object([+            "data": .object([+                "type": .string("reviewSubmissions"),+                "id": .string(submissionID),+                "attributes": .object(["submitted": .bool(true)]),+            ]),+        ]))+        let state = submitted["data"]?["attributes"]?["state"]?.stringValue ?? "SUBMITTED"+        return SubmissionResult(submissionID: submissionID, state: state)+    }++    private func ensureVersion(appID: String, version: String) async throws -> String {+        let existing = try await request(+            method: "GET", path: "/v1/apps/\(appID)/appStoreVersions",+            query: ["filter[versionString]": version, "filter[platform]": "IOS", "fields[appStoreVersions]": "versionString"]+        )+        if let id = existing["data"]?.arrayValue?+            .first(where: { $0["attributes"]?["versionString"]?.stringValue == version })?["id"]?.stringValue {+            return id+        }+        let created = try await request(method: "POST", path: "/v1/appStoreVersions", body: .object([+            "data": .object([+                "type": .string("appStoreVersions"),+                "attributes": .object(["platform": .string("IOS"), "versionString": .string(version)]),+                "relationships": .object([+                    "app": .object(["data": .object(["type": .string("apps"), "id": .string(appID)])])+                ]),+            ]),+        ]))+        guard let id = created["data"]?["id"]?.stringValue else {+            throw Console.Error("appStoreVersions create returned no id: \(created)")+        }+        return id+    }++    private func upsertWhatsNew(versionID: String, whatsNew: String, locale: String) async throws {+        let existing = try await request(+            method: "GET", path: "/v1/appStoreVersions/\(versionID)/appStoreVersionLocalizations",+            query: ["fields[appStoreVersionLocalizations]": "locale,whatsNew"]+        )+        if let locID = existing["data"]?.arrayValue?+            .first(where: { $0["attributes"]?["locale"]?.stringValue == locale })?["id"]?.stringValue {+            _ = try await request(method: "PATCH", path: "/v1/appStoreVersionLocalizations/\(locID)", body: .object([+                "data": .object([+                    "type": .string("appStoreVersionLocalizations"),+                    "id": .string(locID),+                    "attributes": .object(["whatsNew": .string(whatsNew)]),+                ]),+            ]))+        } else {+            _ = try await request(method: "POST", path: "/v1/appStoreVersionLocalizations", body: .object([+                "data": .object([+                    "type": .string("appStoreVersionLocalizations"),+                    "attributes": .object(["locale": .string(locale), "whatsNew": .string(whatsNew)]),+                    "relationships": .object([+                        "appStoreVersion": .object(["data": .object(["type": .string("appStoreVersions"), "id": .string(versionID)])])+                    ]),+                ]),+            ]))+        }+    }++    private func findBuild(appID: String, buildNumber: String, version: String) async throws -> String? {+        let response = try await request(+            method: "GET", path: "/v1/builds",+            query: [+                "filter[app]": appID,+                "filter[version]": buildNumber,+                "sort": "-uploadedDate",+                "limit": "20",+                "fields[builds]": "version,uploadedDate,processingState",+            ]+        )+        return response["data"]?.arrayValue?+            .first { $0["attributes"]?["version"]?.stringValue == buildNumber }?["id"]?.stringValue+    }+}
Sources/XToolSupport/DistCommand.swift
diff --git a/Sources/XToolSupport/DistCommand.swift b/Sources/XToolSupport/DistCommand.swiftnew file mode 100644index 0000000..c1404a4--- /dev/null+++ b/Sources/XToolSupport/DistCommand.swift@@ -0,0 +1,76 @@+import Foundation+import ArgumentParser+import XKit++/// `xtool dist` — App Store Connect distribution (upload + submit).+///+/// Output lines `BUILD_ID:` / `BUILD_STATE:` (upload) and `SUBMISSION_ID:` /+/// `SUBMISSION_STATE:` (submit) are a stable machine-readable contract; the+/// Modern-Apps release pipeline parses them.+struct DistCommand: AsyncParsableCommand {+    static let configuration = CommandConfiguration(+        commandName: "dist",+        abstract: "Upload builds to App Store Connect and submit them for review",+        subcommands: [+            DistUploadCommand.self,+            DistSubmitCommand.self,+        ]+    )+}++struct DistUploadCommand: AsyncParsableCommand {+    static let configuration = CommandConfiguration(+        commandName: "upload",+        abstract: "Upload an .ipa to App Store Connect"+    )++    @Argument(help: "Path to the .ipa to upload")+    var ipaPath: String++    func run() async throws {+        let client = AppStoreConnectClient(key: try resolveASCKey())+        let result = try await client.uploadIPA(at: URL(fileURLWithPath: ipaPath))+        print("BUILD_ID:\(result.buildID)")+        print("BUILD_STATE:\(result.state)")+    }+}++struct DistSubmitCommand: AsyncParsableCommand {+    static let configuration = CommandConfiguration(+        commandName: "submit",+        abstract: "Create/attach the App Store version for a build and submit it for review"+    )++    @Option(help: "Bundle id of the app, e.g. cc.findfamily.app.1")+    var bundleID: String++    @Option(name: .customLong("version"), help: "App Store version string, e.g. 2.6.11")+    var versionString: String++    @Option(help: "Build number (CFBundleVersion) already uploaded and processed")+    var buildNumber: String++    @Option(help: "Path to a plain-text whatsNew file (max 4000 characters)")+    var whatsNew: String++    @Option(help: "Localization locale for whatsNew")+    var locale: String = "en-US"++    func run() async throws {+        let notes = try String(contentsOfFile: whatsNew, encoding: .utf8)+            .trimmingCharacters(in: .whitespacesAndNewlines)+        guard !notes.isEmpty, notes.count <= 4000 else {+            throw Console.Error("whatsNew must be 1...4000 characters (got \(notes.count))")+        }+        let client = AppStoreConnectClient(key: try resolveASCKey())+        let result = try await client.submitForReview(+            bundleID: bundleID,+            version: versionString,+            buildNumber: buildNumber,+            whatsNew: notes,+            locale: locale+        )+        print("SUBMISSION_ID:\(result.submissionID)")+        print("SUBMISSION_STATE:\(result.state)")+    }+}
Sources/XToolSupport/XTool.swift
diff --git a/Sources/XToolSupport/XTool.swift b/Sources/XToolSupport/XTool.swiftindex 2cec336..61fb890 100644--- a/Sources/XToolSupport/XTool.swift+++ b/Sources/XToolSupport/XTool.swift@@ -30,6 +30,7 @@ private struct XToolCommand: AsyncParsableCommand {                     NewCommand.self,                     DevCommand.self,                     DSCommand.self,+                    DistCommand.self,                 ]             ),             CommandGroup(
Tests/XToolTests/DistTests.swift
diff --git a/Tests/XToolTests/DistTests.swift b/Tests/XToolTests/DistTests.swiftnew file mode 100644index 0000000..0d1d819--- /dev/null+++ b/Tests/XToolTests/DistTests.swift@@ -0,0 +1,23 @@+import Foundation+import Testing+@testable import XToolSupport++@Test func ascJSONParsesNestedAppleResponses() throws {+    let json = try ASCJSON(parsing: Data(#"{"data":[{"id":"app1","attributes":{"bundleId":"com.example.app","rank":2,"beta":true}}]}"#.utf8))+    let first = json["data"]?.arrayValue?.first+    #expect(first?["id"]?.stringValue == "app1")+    #expect(first?["attributes"]?["bundleId"]?.stringValue == "com.example.app")+    #expect(first?["attributes"]?["beta"]?.boolValue == true)+    let roundTrip = try ASCJSON(parsing: json.serialize())+    #expect(roundTrip["data"]?.arrayValue?.first?["id"]?.stringValue == "app1")+}++@Test func ascChecksumsMatchKnownVectors() throws {+    let file = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)+    try Data("abc".utf8).write(to: file)+    defer { try? FileManager.default.removeItem(at: file) }+    let sums = try AppStoreConnectClient.checksums(of: file)+    // RFC 1321 / FIPS 180-2 test vectors for "abc".+    #expect(sums.md5 == "900150983cd24fb0d6963f7d28e17f72")+    #expect(sums.sha256 == "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad")+}