Modern Apps git

xtool.git

Public
git clone https://git.maproj.org/xtool.git
main ▾

xtool.git / Sources / XKit / DeveloperServices / App IDs / DeveloperServicesAddAppOperation.swift

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