xtool.git
Publicgit clone https://git.maproj.org/xtool.gitxtool.git / Sources / XKit / DeveloperServices / App IDs / DeveloperServicesAddAppOperation.swift
DeveloperServicesAddAppOperation.swift261 lines · 10.5 KiBRaw
| 1 | // |
| 2 | // DeveloperServicesAddAppOperation.swift |
| 3 | // XKit |
| 4 | // |
| 5 | // Created by Kabir Oberai on 14/10/19. |
| 6 | // Copyright © 2019 Kabir Oberai. All rights reserved. |
| 7 | // |
| 8 | |
| 9 | import Foundation |
| 10 | import DeveloperAPI |
| 11 | |
| 12 | public struct DeveloperServicesAddAppOperation: DeveloperServicesOperation { |
| 13 | |
| 14 | public enum Error: LocalizedError { |
| 15 | case invalidApp(URL) |
| 16 | |
| 17 | public var errorDescription: String? { |
| 18 | switch self { |
| 19 | case .invalidApp(let url): |
| 20 | return url.path.withCString { |
| 21 | String.localizedStringWithFormat( |
| 22 | NSLocalizedString( |
| 23 | "add_app_operation.error.invalid_app", value: "Invalid app: %s", comment: "" |
| 24 | ), $0 |
| 25 | ) |
| 26 | } |
| 27 | } |
| 28 | } |
| 29 | } |
| 30 | |
| 31 | public let context: SigningContext |
| 32 | public let signingInfo: SigningInfo |
| 33 | public let root: URL |
| 34 | public init(context: SigningContext, signingInfo: SigningInfo, root: URL) { |
| 35 | self.context = context |
| 36 | self.signingInfo = signingInfo |
| 37 | self.root = root |
| 38 | } |
| 39 | |
| 40 | /// Registers the app with the given entitlements |
| 41 | private func upsertApp( |
| 42 | bundleID: String, |
| 43 | entitlements: Entitlements, |
| 44 | isFreeTeam: Bool |
| 45 | ) async throws -> Components.Schemas.BundleId { |
| 46 | let newBundleID = ProvisioningIdentifiers.identifier(fromSanitized: bundleID, context: self.context) |
| 47 | |
| 48 | let existing = try await context.developerAPIClient |
| 49 | .bundleIdsGetCollection(query: .init( |
| 50 | filter_lbrack_identifier_rbrack_: [bundleID] |
| 51 | )) |
| 52 | .ok.body.json.data |
| 53 | // filter[identifier] is a prefix filter so we need to manually upgrade to equality |
| 54 | .first(where: { $0.attributes?.identifier == newBundleID }) |
| 55 | |
| 56 | let appID: Components.Schemas.BundleId |
| 57 | if let existing { |
| 58 | appID = existing |
| 59 | } else { |
| 60 | let name = ProvisioningIdentifiers.appName(fromSanitized: bundleID) |
| 61 | let createResponse = try await context.developerAPIClient.bundleIdsCreateInstance( |
| 62 | body: .json( |
| 63 | .init( |
| 64 | data: .init( |
| 65 | _type: .bundleIds, |
| 66 | attributes: .init( |
| 67 | name: name, |
| 68 | platform: .init(.ios), |
| 69 | identifier: newBundleID |
| 70 | ) |
| 71 | ) |
| 72 | ) |
| 73 | ) |
| 74 | ) |
| 75 | appID = try createResponse.created.body.json.data |
| 76 | } |
| 77 | |
| 78 | let existingCapabilitiesList = try await context.developerAPIClient |
| 79 | .bundleIdsBundleIdCapabilitiesGetToManyRelated(.init(path: .init(id: appID.id))) |
| 80 | .ok.body.json.data |
| 81 | let existingCapabilities = [Components.Schemas.CapabilityType: Components.Schemas.BundleIdCapability]( |
| 82 | existingCapabilitiesList.compactMap { cap in |
| 83 | (cap.attributes?.capabilityType).map { ($0, cap) } |
| 84 | }, |
| 85 | uniquingKeysWith: { $1 } |
| 86 | ) |
| 87 | |
| 88 | let wantedCapabilitiesList = try entitlements.entitlements().compactMap(\.anyCapability) |
| 89 | let wantedCapabilities = [Components.Schemas.CapabilityType: [Components.Schemas.CapabilitySetting]]( |
| 90 | wantedCapabilitiesList.map { ($0.capabilityType, $0.settings ?? []) }, |
| 91 | uniquingKeysWith: { $1 } |
| 92 | ) |
| 93 | |
| 94 | for (typ, cap) in existingCapabilities { |
| 95 | if let wantedSettings = wantedCapabilities[typ] { |
| 96 | if wantedSettings != (cap.attributes?.settings ?? []) { |
| 97 | _ = try await context.developerAPIClient.bundleIdCapabilitiesUpdateInstance( |
| 98 | path: .init(id: cap.id), |
| 99 | body: .json( |
| 100 | .init( |
| 101 | data: .init( |
| 102 | _type: .bundleIdCapabilities, |
| 103 | id: cap.id, |
| 104 | attributes: .init( |
| 105 | capabilityType: typ, |
| 106 | settings: wantedSettings |
| 107 | ) |
| 108 | ) |
| 109 | ) |
| 110 | ) |
| 111 | ) |
| 112 | .ok |
| 113 | } |
| 114 | } else { |
| 115 | // DeveloperServices doesn't allow deleting these capabilities |
| 116 | let requiredCapabilities: Set<Components.Schemas.CapabilityType.Value1Payload> = [.inAppPurchase] |
| 117 | if let capType = cap.attributes?.capabilityType?.value1, !requiredCapabilities.contains(capType) { |
| 118 | _ = try await context.developerAPIClient |
| 119 | .bundleIdCapabilitiesDeleteInstance(path: .init(id: cap.id)) |
| 120 | .noContent |
| 121 | } |
| 122 | } |
| 123 | } |
| 124 | for (typ, settings) in wantedCapabilities { |
| 125 | guard existingCapabilities[typ] == nil else { continue } |
| 126 | _ = try await context.developerAPIClient.bundleIdCapabilitiesCreateInstance( |
| 127 | body: .json(.init(data: .init( |
| 128 | _type: .bundleIdCapabilities, |
| 129 | attributes: .init( |
| 130 | capabilityType: typ, |
| 131 | settings: settings |
| 132 | ), |
| 133 | relationships: .init( |
| 134 | bundleId: .init( |
| 135 | data: .init( |
| 136 | _type: .bundleIds, |
| 137 | id: appID.id |
| 138 | ) |
| 139 | ), |
| 140 | // not public but required iff using ds2 API |
| 141 | capability: context.auth.isPublicAPI ? nil : .init( |
| 142 | data: .init( |
| 143 | _type: .capabilities, |
| 144 | id: typ |
| 145 | ) |
| 146 | ) |
| 147 | ) |
| 148 | ))) |
| 149 | ) |
| 150 | .created.body |
| 151 | } |
| 152 | |
| 153 | return appID |
| 154 | } |
| 155 | |
| 156 | /// Registers the app and creates a profile. Returns the resultant entitlements as well as |
| 157 | /// the profile (note that the profile does not necessarily include all of the entitlements |
| 158 | /// that the app has). |
| 159 | private func addApp( |
| 160 | _ app: URL, |
| 161 | isFreeTeam: Bool |
| 162 | ) async throws -> ProvisioningInfo { |
| 163 | let infoURL = app.appendingPathComponent("Info.plist") |
| 164 | guard let data = try? Data(contentsOf: infoURL), |
| 165 | let dict = try? PropertyListSerialization.propertyList(from: data, format: nil) as? [String: Any], |
| 166 | let bundleID = dict["CFBundleIdentifier"] as? String, |
| 167 | let executable = dict["CFBundleExecutable"] as? String else { |
| 168 | throw Error.invalidApp(app) |
| 169 | } |
| 170 | let executableURL = app.appendingPathComponent(executable) |
| 171 | |
| 172 | var entitlements: Entitlements |
| 173 | // if the executable doesn't already have entitlements, that's |
| 174 | // okay. We don't have to throw an error. |
| 175 | if let entitlementsData = try? await context.signer.analyze(executable: executableURL), |
| 176 | let decodedEntitlements = try? PropertyListDecoder().decode(Entitlements.self, from: entitlementsData) { |
| 177 | entitlements = decodedEntitlements |
| 178 | |
| 179 | if isFreeTeam { |
| 180 | // re-assign rather than using updateEntitlements since the latter will |
| 181 | // retain unrecognized entitlements |
| 182 | let filtered = try entitlements.entitlements().filter { $0.anyCapability?.isFree != false } |
| 183 | entitlements = try Entitlements(entitlements: filtered) |
| 184 | } |
| 185 | } else { |
| 186 | entitlements = try Entitlements(entitlements: []) |
| 187 | } |
| 188 | |
| 189 | let appID = try await upsertApp(bundleID: bundleID, entitlements: entitlements, isFreeTeam: isFreeTeam) |
| 190 | let newBundleID = appID.attributes!.identifier! |
| 191 | |
| 192 | let teamID = try signingInfo.certificate.teamID() |
| 193 | try entitlements.update( |
| 194 | teamID: .init(rawValue: teamID), |
| 195 | bundleID: newBundleID |
| 196 | ) |
| 197 | // set get-task-allow to YES, required for dev certs |
| 198 | try entitlements.updateEntitlements { ents in |
| 199 | if let getTaskAllow = ents.firstIndex(where: { $0 is GetTaskAllowEntitlement }) { |
| 200 | ents[getTaskAllow] = GetTaskAllowEntitlement(rawValue: true) |
| 201 | } else { |
| 202 | ents.append(GetTaskAllowEntitlement(rawValue: true)) |
| 203 | } |
| 204 | } |
| 205 | |
| 206 | if var entitlementsArray = try? entitlements.entitlements(), |
| 207 | let groupsIdx = entitlementsArray.firstIndex(where: { $0 is AppGroupEntitlement }), |
| 208 | let groupsEntitlement = entitlementsArray[groupsIdx] as? AppGroupEntitlement { |
| 209 | let groups = groupsEntitlement.rawValue |
| 210 | |
| 211 | if let operation = DeveloperServicesAssignAppGroupsOperation( |
| 212 | context: self.context, |
| 213 | groupIDs: groups, |
| 214 | appID: appID |
| 215 | ) { |
| 216 | let newGroups = try await operation.perform() |
| 217 | entitlementsArray[groupsIdx] = AppGroupEntitlement(rawValue: newGroups) |
| 218 | try entitlements.setEntitlements(entitlementsArray) |
| 219 | } |
| 220 | } |
| 221 | |
| 222 | let mobileprovision = try await DeveloperServicesFetchProfileOperation( |
| 223 | context: self.context, |
| 224 | bundleID: newBundleID, |
| 225 | signingInfo: signingInfo |
| 226 | ).perform() |
| 227 | |
| 228 | return ProvisioningInfo( |
| 229 | newBundleID: newBundleID, |
| 230 | entitlements: entitlements, |
| 231 | mobileprovision: mobileprovision |
| 232 | ) |
| 233 | } |
| 234 | |
| 235 | /// Registers the app + its extensions, returning the profile and entitlements of each |
| 236 | public func perform() async throws -> [URL: ProvisioningInfo] { |
| 237 | var apps: [URL] = [root] |
| 238 | |
| 239 | for pluginsDir in ["PlugIns", "Extensions"] { |
| 240 | let plugins = root.appendingPathComponent(pluginsDir) |
| 241 | guard plugins.dirExists else { continue } |
| 242 | apps += plugins.implicitContents.filter { $0.pathExtension.lowercased() == "appex" } |
| 243 | } |
| 244 | |
| 245 | let isFreeTeam = try await context.auth.team()?.isFree == true |
| 246 | |
| 247 | return try await withThrowingTaskGroup( |
| 248 | of: (URL, ProvisioningInfo).self, |
| 249 | returning: [URL: ProvisioningInfo].self |
| 250 | ) { group in |
| 251 | for app in apps { |
| 252 | group.addTask { |
| 253 | let info = try await addApp(app, isFreeTeam: isFreeTeam) |
| 254 | return (app, info) |
| 255 | } |
| 256 | } |
| 257 | return try await group.reduce(into: [:]) { $0[$1.0] = $1.1 } |
| 258 | } |
| 259 | } |
| 260 | |
| 261 | } |