diff --cc Sources/XToolSupport/AppStoreConnect.swiftindex 0000000,b5fd341..c580d90mode 000000,100644..100644--- a/Sources/XToolSupport/AppStoreConnect.swift+++ b/Sources/XToolSupport/AppStoreConnect.swift@@@ -1,0 -1,462 +1,463 @@@+ import Foundation+ #if canImport(FoundationNetworking)+ import FoundationNetworking+ #endif+ import Crypto+ import XKit+ import XUtils+ import Subprocess++import XCLIUtils+ + /// 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+ }+ }diff --cc Sources/XToolSupport/DistCommand.swiftindex 0000000,c1404a4..9741d25mode 000000,100644..100644--- a/Sources/XToolSupport/DistCommand.swift+++ b/Sources/XToolSupport/DistCommand.swift@@@ -1,0 -1,76 +1,77 @@@+ import Foundation+ import ArgumentParser+ import XKit++import XCLIUtils+ + /// `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)")+ }+ }diff --cc Sources/XToolSupport/DistributionSigning.swiftindex 0000000,a0efeeb..ccac216mode 000000,100644..100644--- a/Sources/XToolSupport/DistributionSigning.swift+++ b/Sources/XToolSupport/DistributionSigning.swift@@@ -1,0 -1,171 +1,176 @@@+ import Foundation+ import DeveloperAPI++import Dependencies+ import XKit++import XCLIUtils+ import Subprocess+ + /// App Store distribution signing for `xtool dev build --distribution app-store`.+ ///+ /// Inputs come from the release-pipeline env contract:+ /// `XTOOL_DIST_P12_PATH` + `XTOOL_DIST_P12_PASSWORD` (a pre-made Apple+ /// Distribution identity) and the App Store Connect API key (see+ /// `resolveASCKey()`). The distribution certificate is extracted from the+ /// P12 with `openssl`, an `IOS_APP_STORE` provisioning profile for the app's+ /// bundle id is fetched (or created) via the ASC API, embedded, and the app+ /// is signed with that identity and the profile's entitlements.+ enum DistributionSigning {+ struct Identity {+ var certificate: Certificate+ var privateKey: PrivateKey+ /// Files holding decrypted key material; deleted after signing.+ var tempDir: URL+ }+ + static func resolveIdentity() async throws -> Identity {+ let env = ProcessInfo.processInfo.environment+ guard let p12Path = env["XTOOL_DIST_P12_PATH"], let password = env["XTOOL_DIST_P12_PASSWORD"] else {+ throw Console.Error("""+ --distribution app-store requires XTOOL_DIST_P12_PATH and \+ XTOOL_DIST_P12_PASSWORD (an Apple Distribution .p12).+ """)+ }+ return try await extractIdentity(p12Path: p12Path, password: password)+ }+ + /// Extracts (cert DER, key PEM) from a PKCS12 using the `openssl` CLI.+ /// `openssl` is present on Linux builders and macOS; parsing PKCS12 in+ ///-process would need an OpenSSL binding xtool does not have.+ static func extractIdentity(p12Path: String, password: String) async throws -> Identity {+ let tempDir = FileManager.default.temporaryDirectory+ .appendingPathComponent("xtool-dist-\(UUID().uuidString)", isDirectory: true)+ try FileManager.default.createDirectory(at: tempDir, withIntermediateDirectories: true)+ try FileManager.default.setAttributes([.posixPermissions: 0o700], ofItemAtPath: tempDir.path)+ + func runOpenSSL(_ arguments: [String]) async throws {+ try await Subprocess.run(+ .name("openssl"),+ arguments: .init(arguments),+ output: .discarded,+ error: .discarded+ ).checkSuccess()+ }+ + let certPEM = tempDir.appendingPathComponent("cert.pem")+ let keyPEM = tempDir.appendingPathComponent("key.pem")+ let certDER = tempDir.appendingPathComponent("cert.der")+ + // OpenSSL 3 may need -legacy for PKCS12 files made by older tooling.+ func extract(_ base: [String]) async throws {+ do {+ try await runOpenSSL(base)+ } catch {+ try await runOpenSSL(base + ["-legacy"])+ }+ }+ try await extract([+ "pkcs12", "-in", p12Path, "-clcerts", "-nokeys",+ "-out", certPEM.path, "-passin", "pass:\(password)",+ ])+ try await extract([+ "pkcs12", "-in", p12Path, "-nocerts", "-nodes",+ "-out", keyPEM.path, "-passin", "pass:\(password)",+ ])+ try await runOpenSSL(["x509", "-in", certPEM.path, "-outform", "DER", "-out", certDER.path])+ try FileManager.default.setAttributes([.posixPermissions: 0o600], ofItemAtPath: keyPEM.path)+ + let certificate = try Certificate(data: Data(contentsOf: certDER))+ let privateKey = PrivateKey(data: try Data(contentsOf: keyPEM))+ return Identity(certificate: certificate, privateKey: privateKey, tempDir: tempDir)+ }+ + /// Signs `app` for App Store distribution in place.+ static func signAppStore(_ app: URL) async throws {+ let identity = try await resolveIdentity()+ defer { try? FileManager.default.removeItem(at: identity.tempDir) }+ + let infoURL = app.appendingPathComponent("Info.plist")+ let infoData = try Data(contentsOf: infoURL)+ guard let info = try PropertyListSerialization.propertyList(from: infoData, format: nil) as? [String: Any],+ let bundleID = info["CFBundleIdentifier"] as? String else {+ throw Console.Error("Could not read CFBundleIdentifier from '\(infoURL.path)'")+ }+ + let key = try resolveASCKey()+ let client = DeveloperAPIClient(auth: .appStoreConnect(key))+ let profile = try await fetchOrCreateAppStoreProfile(+ client: client, bundleID: bundleID, certificate: identity.certificate+ )+ let digest = try profile.digest()+ + let embedded = app.appendingPathComponent("embedded.mobileprovision")+ try? FileManager.default.removeItem(at: embedded)+ try profile.data().write(to: embedded)+ - let signer = try Signer.first()++ @Dependency(\.signer) var signer++ let encoder = PropertyListEncoder()++ encoder.outputFormat = .xml+ try await signer.sign(+ app: app,+ identity: .real(identity.certificate, identity.privateKey), - entitlementMapping: [app: digest.entitlements],++ entitlementMapping: [app: try encoder.encode(digest.entitlements)],++ deep: true,+ progress: { _ in }+ )+ }+ + private static func fetchOrCreateAppStoreProfile(+ client: DeveloperAPIClient,+ bundleID: String,+ certificate: Certificate+ ) async throws -> Mobileprovision {+ let bundleIDs = try await client.bundleIdsGetCollection(query: .init(+ filter_lbrack_identifier_rbrack_: [bundleID]+ )).ok.body.json+ guard let bundleResource = bundleIDs.data.first(where: { $0.attributes?.identifier == bundleID }) else {+ throw Console.Error("No bundle id '\(bundleID)' registered in App Store Connect")+ }+ + // Find the ASC resource for the P12's certificate (matched by serial).+ let certificates = try await DeveloperAPIPages {+ try await client.certificatesGetCollection().ok.body.json+ } next: {+ $0.links.next+ }.map(\.data).reduce(into: [], +=)+ guard let certResource = certificates.first(where: {+ $0.attributes?.serialNumber.map(certificate.hasSerialNumber) == true+ }) else {+ throw Console.Error("Distribution certificate from the P12 is not registered in App Store Connect")+ }+ + // Reuse an active app-store profile for this bundle id when one exists.+ let profiles = try await DeveloperAPIPages {+ try await client.profilesGetCollection().ok.body.json+ } next: {+ $0.links.next+ }.map(\.data).reduce(into: [], +=)+ for profile in profiles {+ guard profile.attributes?.profileType?.value1 == .iosAppStore,+ profile.attributes?.profileState?.value1 == .active,+ profile.relationships?.bundleId?.data?.id == bundleResource.id,+ let content = profile.attributes?.profileContent,+ let data = Data(base64Encoded: content) else { continue }+ return try Mobileprovision(data: data)+ }+ + let created = try await client.profilesCreateInstance(body: .json(.init(+ data: .init(+ _type: .profiles,+ attributes: .init(+ name: "xtool app-store \(bundleID)",+ profileType: .init(.iosAppStore)+ ),+ relationships: .init(+ bundleId: .init(data: .init(_type: .bundleIds, id: bundleResource.id)),+ certificates: .init(data: [.init(_type: .certificates, id: certResource.id)])+ )+ )+ ))).created.body.json.data+ + guard let content = created.attributes?.profileContent,+ let data = Data(base64Encoded: content) else {+ throw Console.Error("Created app-store profile had no profileContent")+ }+ return try Mobileprovision(data: data)+ }+ }