SupersetteADIProvider, more supersign commands, update ldid
- Commit
bc9603a13619953452e5871c453907d9b1240b45- Author
- Kabir Oberai <[email protected]>
- When
- 2022-07-24 19:08 UTC (4 years ago)
- Parents
a702311
Diff
Supersign/Package.swift
diff --git a/Supersign/Package.swift b/Supersign/Package.swiftindex 976d9db..1f2c9c7 100644--- a/Supersign/Package.swift+++ b/Supersign/Package.swift@@ -12,7 +12,7 @@ let package = Package( name: "Supersign", platforms: [ .iOS("13.0"),- .macOS("10.11")+ .macOS("10.15") ], products: [ .library(
Supersign/Sources/Supersign/DeveloperServices/DeveloperServicesClient.swift
diff --git a/Supersign/Sources/Supersign/DeveloperServices/DeveloperServicesClient.swift b/Supersign/Sources/Supersign/DeveloperServices/DeveloperServicesClient.swiftindex 0fb6007..4d0f7ef 100644--- a/Supersign/Sources/Supersign/DeveloperServices/DeveloperServicesClient.swift+++ b/Supersign/Sources/Supersign/DeveloperServices/DeveloperServicesClient.swift@@ -61,13 +61,12 @@ public final class DeveloperServicesClient { public init( loginToken: DeveloperServicesLoginToken, deviceInfo: DeviceInfo,- httpFactory: HTTPClientFactory = defaultHTTPClientFactory,- customAnisetteDataProvider: AnisetteDataProvider? = nil+ anisetteProvider: AnisetteDataProvider,+ httpFactory: HTTPClientFactory = defaultHTTPClientFactory ) { self.loginToken = loginToken self.deviceInfo = deviceInfo- self.anisetteDataProvider = customAnisetteDataProvider- ?? SupersetteDataProvider(deviceInfo: deviceInfo)+ self.anisetteDataProvider = anisetteProvider self.httpClient = httpFactory.makeClient() }
Supersign/Sources/Supersign/DeveloperServices/DeveloperServicesLoginManager.swift
diff --git a/Supersign/Sources/Supersign/DeveloperServices/DeveloperServicesLoginManager.swift b/Supersign/Sources/Supersign/DeveloperServices/DeveloperServicesLoginManager.swiftindex f3e6d6f..68570fd 100644--- a/Supersign/Sources/Supersign/DeveloperServices/DeveloperServicesLoginManager.swift+++ b/Supersign/Sources/Supersign/DeveloperServices/DeveloperServicesLoginManager.swift@@ -32,11 +32,16 @@ public struct DeveloperServicesLoginManager { public init( deviceInfo: DeviceInfo,- customAnisetteProvider: AnisetteDataProvider? = nil- ) {+ anisetteProvider: AnisetteDataProvider,+ httpFactory: HTTPClientFactory = defaultHTTPClientFactory+ ) throws { self.deviceInfo = deviceInfo- self.anisetteProvider = customAnisetteProvider ?? SupersetteDataProvider(deviceInfo: deviceInfo)- self.client = GrandSlamClient(deviceInfo: deviceInfo, customAnisetteDataProvider: anisetteProvider)+ self.anisetteProvider = anisetteProvider+ self.client = GrandSlamClient(+ deviceInfo: deviceInfo,+ anisetteProvider: anisetteProvider,+ httpFactory: httpFactory+ ) } private func logIn(
Supersign/Sources/Supersign/GrandSlam/Anisette/ADIDataProvider.swift
diff --git a/Supersign/Sources/Supersign/GrandSlam/Anisette/ADIDataProvider.swift b/Supersign/Sources/Supersign/GrandSlam/Anisette/ADIDataProvider.swiftnew file mode 100644index 0000000..2c7f638--- /dev/null+++ b/Supersign/Sources/Supersign/GrandSlam/Anisette/ADIDataProvider.swift@@ -0,0 +1,252 @@+import Foundation+import CryptoKit++enum HashingError: Error {+ case hashingFailed+}++private extension String {+ func sha256() throws -> SHA256Digest {+ SHA256.hash(data: Data(utf8))+ }+}++public protocol RawADIProvider {+ func startProvisioning(+ spim: Data,+ completion: @escaping (Result<(String, Data), Error>) -> Void+ )++ func endProvisioning(+ session: String,+ routingInfo: UInt64,+ ptm: Data,+ tk: Data,+ completion: @escaping (Result<Data, Error>) -> Void+ )++ func requestOTP(+ provisioningInfo: Data,+ completion: @escaping (Result<(machineID: Data, otp: Data), Error>) -> Void+ )+}++// uses CoreADI APIs+public final class ADIDataProvider: AnisetteDataProvider {++ public enum ADIError: Error {+ case hashingFailed+ case noResponse+ case badStartResponse+ case badEndResponse+ }++ public let rawProvider: RawADIProvider+ public let deviceInfo: DeviceInfo+ public let storage: KeyValueStorage++ private let httpClient: HTTPClientProtocol+ private let lookupManager: GrandSlamLookupManager+ private let localUserID: String++ public init(+ rawProvider: RawADIProvider,+ deviceInfo: DeviceInfo,+ storage: KeyValueStorage, // ideally secure, eg keychain+ httpFactory: HTTPClientFactory = defaultHTTPClientFactory+ ) throws {+ self.rawProvider = rawProvider+ self.deviceInfo = deviceInfo+ self.storage = storage++ self.httpClient = httpFactory.makeClient()+ self.lookupManager = .init(deviceInfo: deviceInfo, httpFactory: httpFactory)++ if let localUserID = try storage.string(forKey: Self.localUserIDKey) {+ self.localUserID = localUserID+ } else {+ // localUserID = SHA256(local user UID)+ let localUserUID = UUID().uuidString+ let localUserID = try localUserUID.sha256().map { String(format: "%02X", $0) }.joined()+ try storage.setString(localUserID, forKey: Self.localUserIDKey)+ self.localUserID = localUserID+ }+ }++ private static let localUserIDKey = "SUPLocalUserID"+ private static let provisioningKey = "SUPProvisioningInfo"+ private static let routingInfoKey = "SUPRoutingInfo"++ private struct GSARequest<T: Encodable>: Encodable {+ let header: [String: String] = [:]+ let request: T++ private enum CodingKeys: String, CodingKey {+ case header = "Header"+ case request = "Request"+ }+ }++ private struct StartProvisioningRequest: Encodable {}+ private struct StartProvisioningResponse: Decodable {+ let spim: String+ }++ private struct EndProvisioningRequest: Encodable {+ let cpim: String+ }+ private struct EndProvisioningResponse: Decodable {+ let ptm: String // base64+ let tk: String // base64+ let rinfo: String // number (u64)++ private enum CodingKeys: String, CodingKey {+ case ptm+ case tk+ case rinfo = "X-Apple-I-MD-RINFO"+ }+ }++ private static let encoder: PropertyListEncoder = {+ let encoder = PropertyListEncoder()+ encoder.outputFormat = .xml+ return encoder+ }()++ private func sendRequest<Request: Encodable, Response: Decodable>(+ endpoint: GrandSlamEndpoint,+ request: Request,+ completion: @escaping (Result<Response, Error>) -> Void+ ) {+ lookupManager.fetchURL(forEndpoint: endpoint) { result in+ guard let endpointURL = result.get(withErrorHandler: completion) else { return }+ let body: Data+ do {+ body = try Self.encoder.encode(GSARequest(request: request))+ } catch {+ return completion(.failure(error))+ }+ var request = HTTPRequest(+ url: endpointURL,+ method: "POST",+ headers: [+ "Content-Type": "text/x-xml-plist",+ AnisetteData.localUserIDKey: self.localUserID,+ "Accept-Language": "en_US"+ ],+ body: .buffer(body)+ )+ request.headers["X-MMe-Country"] = Locale.current.regionCode++ // Looks like Apple detects attempts to use a macOS client string on Windows :/+ request.headers[DeviceInfo.clientInfoKey] = """+ <PC> <Windows;6.2(0,0);9200> <com.apple.AuthKitWin/1 (com.apple.iCloud/7.21)>+ """+ request.headers[DeviceInfo.deviceIDKey] = self.deviceInfo.deviceID+// request.headers[DeviceInfo.clientInfoKey] = self.deviceInfo.clientInfo.clientString+// self.deviceInfo.dictionary.forEach { request.headers[$0] = $1 }++ self.httpClient.makeRequest(request) { result in+ guard let resp = result.get(withErrorHandler: completion) else { return }+ guard let body = resp.body else { return completion(.failure(ADIError.noResponse)) }+// print(String(data: body, encoding: .utf8) ?? "<no utf8 data>")+ completion(Result {+ try GrandSlamOperationDecoder<Response>.decode(data: body)+ })+ }+ }+ }++ private func endProvisioning(+ id: String,+ cpim: Data,+ completion: @escaping (Result<(routingInfo: UInt64, provisioningInfo: Data), Error>) -> Void+ ) {+ sendRequest(+ endpoint: \.midFinishProvisioning,+ request: EndProvisioningRequest(cpim: cpim.base64EncodedString())+ ) { (result: Result<EndProvisioningResponse, Error>) -> Void in+ guard let resp = result.get(withErrorHandler: completion) else { return }+ guard let rinfo = UInt64(resp.rinfo),+ let ptm = Data(base64Encoded: resp.ptm),+ let tk = Data(base64Encoded: resp.tk)+ else { return completion(.failure(ADIError.badEndResponse)) }+ self.rawProvider.endProvisioning(session: id, routingInfo: rinfo, ptm: ptm, tk: tk) { result in+ guard let provisioningInfo = result.get(withErrorHandler: completion) else { return }+ completion(.success((rinfo, provisioningInfo)))+ }+ }+ }++ private func provision(completion: @escaping (Result<(routingInfo: UInt64, provisioningInfo: Data), Error>) -> Void) {+ sendRequest(+ endpoint: \.midStartProvisioning,+ request: StartProvisioningRequest()+ ) { (result: Result<StartProvisioningResponse, Error>) -> Void in+ guard let resp = result.get(withErrorHandler: completion) else { return }+ guard let spim = Data(base64Encoded: resp.spim) else {+ return completion(.failure(ADIError.badStartResponse))+ }+ self.rawProvider.startProvisioning(spim: spim) { result in+ guard let (id, cpim) = result.get(withErrorHandler: completion) else { return }+ self.endProvisioning(id: id, cpim: cpim, completion: completion)+ }+ }+ }++ private func fetchAnisetteData(+ routingInfo: UInt64,+ provisioningInfo: Data,+ completion: @escaping (Result<AnisetteData, Error>) -> Void+ ) {+ let requestTime = Date()+ rawProvider.requestOTP(provisioningInfo: provisioningInfo) { result in+ guard let (mid, otp) = result.get(withErrorHandler: completion) else { return }+ completion(.success(AnisetteData(+ clientTime: requestTime,+ routingInfo: routingInfo,+ machineID: mid.base64EncodedString(),+ localUserID: self.localUserID,+ oneTimePassword: otp.base64EncodedString()+ )))+ }+ }++ public func resetProvisioning(completion: @escaping (Result<Void, Error>) -> Void) {+ completion(Result {+ try storage.setData(nil, forKey: Self.provisioningKey)+ try storage.setString(nil, forKey: Self.routingInfoKey)+ })+ }++ public func fetchAnisetteData(completion: @escaping (Result<AnisetteData, Error>) -> Void) {+ do {+ if let provisioningInfo = try storage.data(forKey: Self.provisioningKey),+ let routingInfoString = try storage.string(forKey: Self.routingInfoKey),+ let routingInfo = UInt64(routingInfoString) {+ return fetchAnisetteData(+ routingInfo: routingInfo,+ provisioningInfo: provisioningInfo,+ completion: completion+ )+ }+ } catch {+ return completion(.failure(error))+ }+ provision { result in+ guard let (rinfo, data) = result.get(withErrorHandler: completion) else { return }+ do {+ try self.storage.setData(data, forKey: Self.provisioningKey)+ try self.storage.setString("\(rinfo)", forKey: Self.routingInfoKey)+ } catch {+ return completion(.failure(error))+ }+ self.fetchAnisetteData(+ routingInfo: rinfo,+ provisioningInfo: data,+ completion: completion+ )+ }+ }++}
Supersign/Sources/Supersign/GrandSlam/Anisette/AnisetteDataProvider.swift
diff --git a/Supersign/Sources/Supersign/GrandSlam/Anisette/AnisetteDataProvider.swift b/Supersign/Sources/Supersign/GrandSlam/Anisette/AnisetteDataProvider.swiftindex ae708da..85341fe 100644--- a/Supersign/Sources/Supersign/GrandSlam/Anisette/AnisetteDataProvider.swift+++ b/Supersign/Sources/Supersign/GrandSlam/Anisette/AnisetteDataProvider.swift@@ -9,5 +9,13 @@ import Foundation public protocol AnisetteDataProvider {+ // This is a suggestion and not a requirement. The default implementation+ // does nothing.+ func resetProvisioning(completion: @escaping (Result<Void, Error>) -> Void)+ func fetchAnisetteData(completion: @escaping (Result<AnisetteData, Error>) -> Void) }++extension AnisetteDataProvider {+ public func resetProvisioning(completion: @escaping (Result<Void, Error>) -> Void) {}+}
Supersign/Sources/Supersign/GrandSlam/Anisette/Supersette/SupersetteADIProvider.swift
diff --git a/Supersign/Sources/Supersign/GrandSlam/Anisette/Supersette/SupersetteADIProvider.swift b/Supersign/Sources/Supersign/GrandSlam/Anisette/Supersette/SupersetteADIProvider.swiftnew file mode 100644index 0000000..196db36--- /dev/null+++ b/Supersign/Sources/Supersign/GrandSlam/Anisette/Supersette/SupersetteADIProvider.swift@@ -0,0 +1,130 @@+import Foundation++public class SupersetteADIProvider: RawADIProvider {+ private static let gateway = "http://kabir-winvm.local:3000/v1"++ private static let encoder = JSONEncoder()+ private static let decoder = JSONDecoder()++ public enum Error: Swift.Error {+ case networkError+ case invalidResponse+ }++ public let deviceInfo: DeviceInfo+ private let httpClient: HTTPClientProtocol++ public init(deviceInfo: DeviceInfo, httpFactory: HTTPClientFactory = defaultHTTPClientFactory) {+ self.deviceInfo = deviceInfo+ self.httpClient = httpFactory.makeClient()+ }++ private func makeRequest<Request: Encodable, Response: Decodable>(+ endpoint: StaticString,+ request: Request,+ completion: @escaping (Result<Response, Swift.Error>) -> Void+ ) {+ let url = URL(string: "\(Self.gateway)/\(endpoint)")!+ var httpRequest = HTTPRequest(url: url, method: "POST")+ httpRequest.headers = [+ "Content-Type": "application/json",+ "Accept": "application/json",+ "Superkey": "BF95B548-3C87-4BBD-8B96-534421368416"+ ]+ do {+ httpRequest.body = try .buffer(Self.encoder.encode(request))+ } catch {+ return completion(.failure(error))+ }+// print("Requesting \(endpoint):")+// dump(request)+ httpClient.makeRequest(httpRequest) { result in+ let result = Result { () throws -> Response in+ let resp = try result.get()+ let data = try resp.body.orThrow(Error.invalidResponse)+ return try Self.decoder.decode(Response.self, from: data)+ }+// print("Response for \(endpoint):")+// dump(result)+ completion(result)+ }+ }++ public func startProvisioning(+ spim: Data,+ completion: @escaping (Result<(String, Data), Swift.Error>) -> Void+ ) {+ struct Request: Encodable {+ let spim: Data+ }+ struct Response: Decodable {+ let sessionID: String+ let cpim: Data+ }+ makeRequest(+ endpoint: "start-provisioning",+ request: Request(spim: spim)+ ) { (res: Result<Response, Swift.Error>) -> Void in+ completion(res.map { ($0.sessionID, $0.cpim) })+ }+ }++ public func endProvisioning(+ session: String,+ routingInfo: UInt64,+ ptm: Data,+ tk: Data,+ completion: @escaping (Result<Data, Swift.Error>) -> Void+ ) {+ struct Request: Encodable {+ let session: String+ let rinfo: String+ let ptm: Data+ let tk: Data+ }+ struct Response: Decodable {+ let provisioningInfo: Data+ }+ makeRequest(+ endpoint: "end-provisioning",+ request: Request(session: session, rinfo: "\(routingInfo)", ptm: ptm, tk: tk)+ ) { (res: Result<Response, Swift.Error>) -> Void in+ completion(res.map { $0.provisioningInfo })+ }+ }++ public func requestOTP(+ provisioningInfo: Data,+ completion: @escaping (Result<(machineID: Data, otp: Data), Swift.Error>) -> Void+ ) {+ struct Request: Encodable {+ let provisioningInfo: Data+ }+ struct Response: Decodable {+ let mid: Data+ let otp: Data+ }+ makeRequest(+ endpoint: "otp",+ request: Request(provisioningInfo: provisioningInfo)+ ) { (res: Result<Response, Swift.Error>) -> Void in+ completion(res.map { ($0.mid, $0.otp) })+ }+ }++}++extension ADIDataProvider {+ public static func supersetteProvider(+ deviceInfo: DeviceInfo,+ storage: KeyValueStorage,+ httpFactory: HTTPClientFactory = defaultHTTPClientFactory+ ) throws -> ADIDataProvider {+ return try ADIDataProvider(+ rawProvider: SupersetteADIProvider(deviceInfo: deviceInfo, httpFactory: httpFactory),+ deviceInfo: deviceInfo,+ storage: storage,+ httpFactory: httpFactory+ )+ }+}
Supersign/Sources/Supersign/GrandSlam/GrandSlamClient.swift
diff --git a/Supersign/Sources/Supersign/GrandSlam/GrandSlamClient.swift b/Supersign/Sources/Supersign/GrandSlam/GrandSlamClient.swiftindex 29062d0..ecbe118 100644--- a/Supersign/Sources/Supersign/GrandSlam/GrandSlamClient.swift+++ b/Supersign/Sources/Supersign/GrandSlam/GrandSlamClient.swift@@ -19,12 +19,11 @@ class GrandSlamClient { private let httpClient: HTTPClientProtocol init( deviceInfo: DeviceInfo,- httpFactory: HTTPClientFactory = defaultHTTPClientFactory,- customAnisetteDataProvider: AnisetteDataProvider? = nil+ anisetteProvider: AnisetteDataProvider,+ httpFactory: HTTPClientFactory = defaultHTTPClientFactory ) { self.deviceInfo = deviceInfo- self.anisetteDataProvider = customAnisetteDataProvider- ?? SupersetteDataProvider(deviceInfo: deviceInfo)+ self.anisetteDataProvider = anisetteProvider self.lookupManager = .init(deviceInfo: deviceInfo, httpFactory: httpFactory) self.httpClient = httpFactory.makeClient() }
Supersign/Sources/Supersign/GrandSlam/Lookup/GrandSlamEndpoints.swift
diff --git a/Supersign/Sources/Supersign/GrandSlam/Lookup/GrandSlamEndpoints.swift b/Supersign/Sources/Supersign/GrandSlam/Lookup/GrandSlamEndpoints.swiftindex 79f5e4b..6021ddf 100644--- a/Supersign/Sources/Supersign/GrandSlam/Lookup/GrandSlamEndpoints.swift+++ b/Supersign/Sources/Supersign/GrandSlam/Lookup/GrandSlamEndpoints.swift@@ -13,6 +13,8 @@ struct GrandSlamEndpoints: Decodable { let secondaryAuth: String let trustedDeviceSecondaryAuth: String let validateCode: String+ let midStartProvisioning: String+ let midFinishProvisioning: String } typealias GrandSlamEndpoint = KeyPath<GrandSlamEndpoints, String>
Supersign/Sources/Supersign/Installation/ConnectionManager.swift
diff --git a/Supersign/Sources/Supersign/Installation/ConnectionManager.swift b/Supersign/Sources/Supersign/Installation/ConnectionManager.swiftindex 7a06208..772cba0 100644--- a/Supersign/Sources/Supersign/Installation/ConnectionManager.swift+++ b/Supersign/Sources/Supersign/Installation/ConnectionManager.swift@@ -13,7 +13,7 @@ public protocol ConnectionManagerDelegate: AnyObject { func connectionManager(_ manager: ConnectionManager, clientsDidChangeFrom oldValue: [ConnectionManager.Client]) } -public class ConnectionManager {+public final class ConnectionManager { public enum SearchMode: CaseIterable { case usb@@ -75,7 +75,7 @@ public class ConnectionManager { } } - public class Client {+ public final class Client { private let key: ConnectionKey private let value: ConnectionValue
Supersign/Sources/Supersign/Integration/SuperchargeInstaller.swift
diff --git a/Supersign/Sources/Supersign/Integration/SuperchargeInstaller.swift b/Supersign/Sources/Supersign/Integration/SuperchargeInstaller.swiftindex 4f7bf45..34b767c 100644--- a/Supersign/Sources/Supersign/Integration/SuperchargeInstaller.swift+++ b/Supersign/Sources/Supersign/Integration/SuperchargeInstaller.swift@@ -21,7 +21,7 @@ public protocol IntegratedInstallerDelegate: AnyObject { func fetchTeam(fromTeams teams: [DeveloperServicesTeam], completion: @escaping (DeveloperServicesTeam?) -> Void) func setPresentedMessage(_ message: IntegratedInstaller.Message?) func installerDidUpdate(toStage stage: String, progress: Double?)- func installerDidComplete(withResult result: Result<(), Error>)+ func installerDidComplete(withResult result: Result<String, Error>) // defaults to always returning true func confirmRevocation(of certificates: [DeveloperServicesCertificate], completion: @escaping (Bool) -> Void)@@ -98,8 +98,8 @@ public final class IntegratedInstaller { let connectionPreferences: Connection.Preferences let appleID: String let credentials: Credentials- let signingInfoManager: SigningInfoManager let configureDevice: Bool+ let storage: KeyValueStorage public weak var delegate: IntegratedInstallerDelegate? private var appInstaller: AppInstaller?@@ -128,7 +128,7 @@ public final class IntegratedInstaller { } } - private func completion(_ result: Result<(), Swift.Error>) {+ private func completion(_ result: Result<String, Swift.Error>) { executionStateLock.lock() defer { executionStateLock.unlock() } guard executionState != .complete else { return }@@ -164,7 +164,7 @@ public final class IntegratedInstaller { appleID: String, credentials: Credentials, configureDevice: Bool,- signingInfoManager: SigningInfoManager,+ storage: KeyValueStorage, delegate: IntegratedInstallerDelegate ) { self.udid = udid@@ -172,7 +172,7 @@ public final class IntegratedInstaller { self.appleID = appleID self.credentials = credentials self.configureDevice = configureDevice- self.signingInfoManager = signingInfoManager+ self.storage = storage self.delegate = delegate } @@ -291,7 +291,8 @@ public final class IntegratedInstaller { token: DeveloperServicesLoginToken, client: DeveloperServicesClient, team: DeveloperServicesTeam,- ipa: URL+ ipa: URL,+ bundleID: String ) { guard shouldContinue() else { return } executionStateLock.lock()@@ -303,7 +304,7 @@ public final class IntegratedInstaller { _ = self.updateStage(to: stage.displayName, ignoreCancellation: true) _ = self.updateProgress(to: stage.displayProgress, ignoreCancellation: true) },- completion: completion+ completion: { self.completion($0.map { bundleID }) } ) } @@ -312,7 +313,8 @@ public final class IntegratedInstaller { token: DeveloperServicesLoginToken, client: DeveloperServicesClient, team: DeveloperServicesTeam,- appDir: URL+ appDir: URL,+ bundleID: String ) { guard self.updateStage(to: "Packaging", initialProgress: nil) else { return }@@ -331,7 +333,8 @@ public final class IntegratedInstaller { token: token, client: client, team: team,- ipa: ipa+ ipa: ipa,+ bundleID: bundleID ) } }@@ -365,7 +368,7 @@ public final class IntegratedInstaller { deviceName: deviceName, teamID: team.id, client: client,- signingInfoManager: signingInfoManager,+ signingInfoManager: KeyValueSigningInfoManager(storage: storage), platform: .iOS ) } catch {@@ -400,20 +403,30 @@ public final class IntegratedInstaller { } }, completion: { result in- guard result.get(withErrorHandler: self.completion) != nil else { return }+ guard let bundleID = result.get(withErrorHandler: self.completion) else { return } self.packageAndInstall( deviceInfo: deviceInfo, token: token, client: client, team: team,- appDir: appDir+ appDir: appDir,+ bundleID: bundleID ) } ) } - private func install(deviceInfo: DeviceInfo, token: DeveloperServicesLoginToken, appDir: URL) {- let client = DeveloperServicesClient(loginToken: token, deviceInfo: deviceInfo)+ private func install(+ deviceInfo: DeviceInfo,+ token: DeveloperServicesLoginToken,+ anisetteProvider: AnisetteDataProvider,+ appDir: URL+ ) {+ let client = DeveloperServicesClient(+ loginToken: token,+ deviceInfo: deviceInfo,+ anisetteProvider: anisetteProvider+ ) client.send(DeveloperServicesListTeamsRequest()) { result in guard let teams = result.get(withErrorHandler: self.completion) else { return } guard self.updateProgress(to: 1) else { return }@@ -445,19 +458,38 @@ public final class IntegratedInstaller { guard updateStage(to: "Logging in") else { return } - switch credentials {- case .password(let password):- DeveloperServicesLoginManager(deviceInfo: deviceInfo).logIn(- withUsername: self.appleID,- password: password,- twoFactorDelegate: self- ) { result in- guard let token = result.get(withErrorHandler: self.completion) else { return }- guard self.updateProgress(to: 1/2) else { return }- self.install(deviceInfo: deviceInfo, token: token, appDir: appDir)+ do {+ let anisetteProvider = SupersetteDataProvider(deviceInfo: deviceInfo)+// let anisetteProvider = try ADIDataProvider.supersetteProvider(deviceInfo: deviceInfo, storage: storage)+ switch credentials {+ case .password(let password):+ try DeveloperServicesLoginManager(+ deviceInfo: deviceInfo,+ anisetteProvider: anisetteProvider+ ).logIn(+ withUsername: self.appleID,+ password: password,+ twoFactorDelegate: self+ ) { result in+ guard let token = result.get(withErrorHandler: self.completion) else { return }+ guard self.updateProgress(to: 1/2) else { return }+ self.install(+ deviceInfo: deviceInfo,+ token: token,+ anisetteProvider: anisetteProvider,+ appDir: appDir+ )+ }+ case .token(let token):+ self.install(+ deviceInfo: deviceInfo,+ token: token,+ anisetteProvider: anisetteProvider,+ appDir: appDir+ ) }- case .token(let token):- self.install(deviceInfo: deviceInfo, token: token, appDir: appDir)+ } catch {+ return completion(.failure(error)) } }
Supersign/Sources/Supersign/Signer/Signer.swift
diff --git a/Supersign/Sources/Supersign/Signer/Signer.swift b/Supersign/Sources/Supersign/Signer/Signer.swiftindex 02705e9..602b54c 100644--- a/Supersign/Sources/Supersign/Signer/Signer.swift+++ b/Supersign/Sources/Supersign/Signer/Signer.swift@@ -104,7 +104,7 @@ public struct Signer { status: @escaping (String) -> Void, progress: @escaping (Double) -> Void, didProvision: @escaping () throws -> Void = {},- completion: @escaping (Result<(), Swift.Error>) -> Void+ completion: @escaping (Result<String, Swift.Error>) -> Void ) { status(NSLocalizedString("signer.provisioning", value: "Provisioning", comment: "")) DeveloperServicesProvisioningOperation(@@ -114,15 +114,19 @@ public struct Signer { progress: progress ).perform { result in guard let response = result.get(withErrorHandler: completion) else { return }+ guard let mainInfo = response.provisioningDict[app] else {+ return completion(.failure(Error.errorReading("app bundle ID")))+ } self.sign( app: app, signingInfo: response.signingInfo, provisioningDict: response.provisioningDict, status: status, progress: progress,- didProvision: didProvision,- completion: completion- )+ didProvision: didProvision+ ) {+ completion($0.map { mainInfo.newBundleID })+ } } }
Supersign/Sources/Supersign/Signer/SignerImpl.swift
diff --git a/Supersign/Sources/Supersign/Signer/SignerImpl.swift b/Supersign/Sources/Supersign/Signer/SignerImpl.swiftindex 7594479..8410509 100644--- a/Supersign/Sources/Supersign/Signer/SignerImpl.swift+++ b/Supersign/Sources/Supersign/Signer/SignerImpl.swift@@ -105,12 +105,21 @@ public struct SignerImpl { let privBase = priv.baseAddress else { throw Error.signer(nil) } + let box = Unmanaged.passRetained(progress as AnyObject)+ defer { box.release() } guard signer.pointee.sign( app.path, certBase, cert.count, privBase, priv.count, entsArray, entsArray.count,- progress,+ {+ (Unmanaged<AnyObject>+ .fromOpaque($0)+ .takeUnretainedValue()+ as! (Double) -> Void+ )($1)+ },+ box.toOpaque(), &exception ) == 0 else { throw Error.signer(exception.map { String(cString: $0) })
Supersign/Sources/Supersign/Utilities/KeyValueStorage.swift
diff --git a/Supersign/Sources/Supersign/Utilities/KeyValueStorage.swift b/Supersign/Sources/Supersign/Utilities/KeyValueStorage.swiftindex 4a19e4d..cbd95e8 100644--- a/Supersign/Sources/Supersign/Utilities/KeyValueStorage.swift+++ b/Supersign/Sources/Supersign/Utilities/KeyValueStorage.swift@@ -43,6 +43,48 @@ extension KeyValueStorage { } } +public class MemoryKeyValueStorage: KeyValueStorage {++ private var dict: [String: Data] = [:]+ public init() {}++ public func data(forKey key: String) throws -> Data? {+ dict[key]+ }++ public func setData(_ data: Data?, forKey key: String) throws {+ dict[key] = data+ }++}++public struct DirectoryStorage: KeyValueStorage {+ let base: URL+ public init(base: URL) {+ self.base = base+ }++ private func url(for key: String) -> URL {+ base.appendingPathComponent(key)+ }++ public func data(forKey key: String) throws -> Data? {+ try? Data(contentsOf: url(for: key))+ }++ public func setData(_ data: Data?, forKey key: String) throws {+ let url = url(for: key)+ if !FileManager.default.fileExists(atPath: url.deletingLastPathComponent().path) {+ try FileManager.default.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true)+ }+ if let data = data {+ try data.write(to: url)+ } else {+ try FileManager.default.removeItem(at: url)+ }+ }+}+ #if canImport(Security) import Security
Supersign/Tests/SupersignTests/Tests/SupersignDeveloperServicesTests.swift
diff --git a/Supersign/Tests/SupersignTests/Tests/SupersignDeveloperServicesTests.swift b/Supersign/Tests/SupersignTests/Tests/SupersignDeveloperServicesTests.swiftindex 51dbaed..8647a84 100644--- a/Supersign/Tests/SupersignTests/Tests/SupersignDeveloperServicesTests.swift+++ b/Supersign/Tests/SupersignTests/Tests/SupersignDeveloperServicesTests.swift@@ -12,12 +12,14 @@ import Supersign class SupersignDeveloperServicesTests: XCTestCase { + var storage: KeyValueStorage! var client: DeveloperServicesClient! override func setUp() { super.setUp() _ = addMockSigner- client = .test()+ storage = MemoryKeyValueStorage()+ client = try! .test(storage: storage) } override func tearDown() {@@ -42,8 +44,12 @@ class SupersignDeveloperServicesTests: XCTestCase { )) let waiter = ResultWaiter<DeveloperServicesProvisioningOperation.Response>(description: "Failed to provision")- DeveloperServicesProvisioningOperation(context: context, app: source) { _ in }- .perform(completion: waiter.completion)+ DeveloperServicesProvisioningOperation(+ context: context,+ app: source,+ confirmRevocation: { $1(true) },+ progress: { _ in }+ ).perform(completion: waiter.completion) let response = try XCTTry(waiter.wait(timeout: 10000)) print(response)
Supersign/Tests/SupersignTests/Tests/SupersignGrandSlamTests.swift
diff --git a/Supersign/Tests/SupersignTests/Tests/SupersignGrandSlamTests.swift b/Supersign/Tests/SupersignTests/Tests/SupersignGrandSlamTests.swiftindex 2a1fad2..5a3a606 100644--- a/Supersign/Tests/SupersignTests/Tests/SupersignGrandSlamTests.swift+++ b/Supersign/Tests/SupersignTests/Tests/SupersignGrandSlamTests.swift@@ -20,12 +20,14 @@ class TwoFactorAuthenticator: TwoFactorAuthDelegate { class SupersignGrandSlamTests: XCTestCase { var authenticator: TwoFactorAuthenticator!+ var storage: KeyValueStorage! var client: GrandSlamClient! override func setUp() { super.setUp() _ = addMockSigner- client = .test()+ storage = MemoryKeyValueStorage()+ client = try! .test(storage: storage) authenticator = TwoFactorAuthenticator() }
Supersign/Tests/SupersignTests/Utilities/DeveloperServicesClient+Testing.swift
diff --git a/Supersign/Tests/SupersignTests/Utilities/DeveloperServicesClient+Testing.swift b/Supersign/Tests/SupersignTests/Utilities/DeveloperServicesClient+Testing.swiftindex e7c1821..d6f6039 100644--- a/Supersign/Tests/SupersignTests/Utilities/DeveloperServicesClient+Testing.swift+++ b/Supersign/Tests/SupersignTests/Utilities/DeveloperServicesClient+Testing.swift@@ -30,20 +30,20 @@ extension NetcatAnisetteDataProvider { #endif -extension SupersetteDataProvider {+extension ADIDataProvider { - static func test() -> SupersetteDataProvider {- SupersetteDataProvider(deviceInfo: Config.current.deviceInfo)+ static func test(storage: KeyValueStorage) throws -> ADIDataProvider {+ try supersetteProvider(deviceInfo: Config.current.deviceInfo, storage: storage) } } extension GrandSlamClient { - static func test() -> GrandSlamClient {- GrandSlamClient(+ static func test(storage: KeyValueStorage) throws -> GrandSlamClient {+ try GrandSlamClient( deviceInfo: Config.current.deviceInfo,- customAnisetteDataProvider: SupersetteDataProvider.test()+ anisetteProvider: ADIDataProvider.test(storage: storage) ) } @@ -51,11 +51,11 @@ extension GrandSlamClient { extension DeveloperServicesClient { - static func test() -> DeveloperServicesClient {- DeveloperServicesClient(+ static func test(storage: KeyValueStorage) throws -> DeveloperServicesClient {+ try DeveloperServicesClient( loginToken: Config.current.appleID.token, deviceInfo: Config.current.deviceInfo,- customAnisetteDataProvider: SupersetteDataProvider.test()+ anisetteProvider: ADIDataProvider.test(storage: storage) ) }
SupersignCLISupport/Sources/SupersignCLI/main.swift
diff --git a/SupersignCLISupport/Sources/SupersignCLI/main.swift b/SupersignCLISupport/Sources/SupersignCLI/main.swiftindex 229e7ea..093147e 100644--- a/SupersignCLISupport/Sources/SupersignCLI/main.swift+++ b/SupersignCLISupport/Sources/SupersignCLI/main.swift@@ -10,22 +10,20 @@ moduleBundle = Bundle(url: Bundle.main.url(forResource: "SupersignCLISupport_Sup #endif let app = moduleBundle.url(forResource: "Supercharge", withExtension: "ipa")! -#warning("Persist manager on Windows/Linux")+#warning("Improve persistence on Windows/Linux") // for Windows, we could use dpapi.h or wincred.h. // for Linux, maybe use libsecret? // see https://github.com/atom/node-keytar -let signingInfoManager: SigningInfoManager+let storage: KeyValueStorage #if os(macOS)-signingInfoManager = KeyValueSigningInfoManager(- storage: KeychainStorage(service: "com.kabiroberai.Supercharge-Keychain.credentials")-)+storage = KeychainStorage(service: "com.kabiroberai.Supercharge-Keychain.credentials") #else-signingInfoManager = MemoryBackedSigningInfoManager()+storage = DirectoryStorage(base: URL(fileURLWithPath: "storage", isDirectory: true)) #endif try SupersignCLI.run(configuration: SupersignCLI.Configuration( superchargeApp: app,- signingInfoManager: signingInfoManager+ storage: storage ))
SupersignCLISupport/Sources/SupersignCLISupport/ConnectionDelegate.swift
diff --git a/SupersignCLISupport/Sources/SupersignCLISupport/ConnectionDelegate.swift b/SupersignCLISupport/Sources/SupersignCLISupport/ConnectionDelegate.swiftindex 3f7e777..72449c4 100644--- a/SupersignCLISupport/Sources/SupersignCLISupport/ConnectionDelegate.swift+++ b/SupersignCLISupport/Sources/SupersignCLISupport/ConnectionDelegate.swift@@ -1,5 +1,6 @@ import Foundation import Supersign+import ArgumentParser class ConnectionDelegate: ConnectionManagerDelegate { var onConnect: (([ConnectionManager.Client]) -> Void)?@@ -14,3 +15,38 @@ class ConnectionDelegate: ConnectionManagerDelegate { onConnect = nil } }++extension ConnectionManager.Client: ExpressibleByArguments {+ public struct Arguments: ParsableArguments {+ @Option(name: .shortAndLong) var udid: String?+ @Flag var search: ConnectionManager.SearchMode = .all+ public init() {}+ }++ public static func from(_ args: Arguments) throws -> ConnectionManager.Client {+ print("Waiting for device to be connected...")+ var clients: [ConnectionManager.Client]!+ let semaphore = DispatchSemaphore(value: 0)+ let connDelegate = ConnectionDelegate { currClients in+ if let udid = args.udid {+ if let client = currClients.first(where: { $0.udid == udid }) {+ clients = [client]+ } else {+ clients = []+ }+ } else {+ clients = currClients+ }+ semaphore.signal()+ }+ try withExtendedLifetime(ConnectionManager(searchMode: args.search, delegate: connDelegate)) {+ semaphore.wait()+ }+ return try Console.choose(+ from: clients,+ onNoElement: { throw ValidationError("Device not found") },+ multiPrompt: "Choose device",+ formatter: { "\($0.deviceName) (\($0.connectionType), udid: \($0.udid))" }+ )+ }+}
SupersignCLISupport/Sources/SupersignCLISupport/Console.swift
diff --git a/SupersignCLISupport/Sources/SupersignCLISupport/Console.swift b/SupersignCLISupport/Sources/SupersignCLISupport/Console.swiftindex 1f45c34..8044e8c 100644--- a/SupersignCLISupport/Sources/SupersignCLISupport/Console.swift+++ b/SupersignCLISupport/Sources/SupersignCLISupport/Console.swift@@ -6,9 +6,19 @@ enum Console { if !message.isEmpty { print(message, terminator: "") }+ fflush(stdout) return readLine() } + static func getPassword(_ message: String) -> String? {+ if !message.isEmpty {+ print(message, terminator: "")+ }+ let password = withoutEcho { prompt("") }+ print()+ return password+ }+ private static func withoutEcho<T>(_ action: () throws -> T) rethrows -> T { #if os(Windows) // based on https://stackoverflow.com/a/4497117/3769927@@ -34,19 +44,10 @@ enum Console { return try action() } - static func getPassword(_ message: String) -> String? {- if !message.isEmpty {- print(message, terminator: "")- }- let password = withoutEcho { prompt("") }- print()- return password- }- static func chooseNumber(in range: Range<Int>) -> Int {+ let message = "Choice (\(range.lowerBound)-\(range.upperBound - 1)): " while true {- print("Choice (\(range.lowerBound)-\(range.upperBound - 1)): ", terminator: "")- if let choice = readLine().flatMap(Int.init), range.contains(choice) {+ if let choice = prompt(message).flatMap(Int.init), range.contains(choice) { return choice } }
SupersignCLISupport/Sources/SupersignCLISupport/DSCommand.swift
diff --git a/SupersignCLISupport/Sources/SupersignCLISupport/DSCommand.swift b/SupersignCLISupport/Sources/SupersignCLISupport/DSCommand.swiftindex 1307b52..b239e92 100644--- a/SupersignCLISupport/Sources/SupersignCLISupport/DSCommand.swift+++ b/SupersignCLISupport/Sources/SupersignCLISupport/DSCommand.swift@@ -12,16 +12,34 @@ extension DeviceInfo { } private extension AuthToken {- static func retrieve(deviceInfo: DeviceInfo, username: String?, password: String?) throws -> Self {+ static func retrieve(+ deviceInfo: DeviceInfo,+ username: String?,+ password: String?,+ resetProvisioning: Bool = false+ ) throws -> Self { guard let username = username ?? Console.prompt("Apple ID: "), !username.isEmpty else { throw Console.Error("A non-empty Apple ID is required.") } guard let password = password ?? Console.getPassword("Password: "), !password.isEmpty else { throw Console.Error("A non-empty password is required.") }++ let provider = SupersetteDataProvider(deviceInfo: deviceInfo)+// let provider = try ADIDataProvider.supersetteProvider(+// deviceInfo: deviceInfo,+// storage: SupersignCLI.config.storage+// )+ if resetProvisioning {+ try withSyncContinuation(provider.resetProvisioning(completion:))+ } let authDelegate = SupersignCLIAuthDelegate()+ let manager = try DeveloperServicesLoginManager(+ deviceInfo: deviceInfo,+ anisetteProvider: provider+ ) let token: DeveloperServicesLoginToken = try withSyncContinuation { cont in- DeveloperServicesLoginManager(deviceInfo: deviceInfo).logIn(+ manager.logIn( withUsername: username, password: password, twoFactorDelegate: authDelegate,@@ -47,11 +65,17 @@ struct DSLoginCommand: ParsableCommand { abstract: "Obtain an Apple ID authentication token" ) + @Flag(name: [.short, .long]) var resetProvisioning = false @Option(name: [.short, .long], help: "Apple ID") var username: String? @Option(name: [.short, .long]) var password: String? func run() throws {- let fullToken = try AuthToken.retrieve(deviceInfo: .fetch(), username: self.username, password: self.password)+ let fullToken = try AuthToken.retrieve(+ deviceInfo: .fetch(),+ username: self.username,+ password: self.password,+ resetProvisioning: resetProvisioning+ ) guard let string = fullToken.string else { throw Console.Error("Could not encode token.") }@@ -69,8 +93,17 @@ struct DSTeamsListCommand: ParsableCommand { func run() throws { let deviceInfo = try DeviceInfo.fetch()+ let anisetteProvider = SupersetteDataProvider(deviceInfo: deviceInfo)+// let anisetteProvider = try ADIDataProvider.supersetteProvider(+// deviceInfo: deviceInfo, storage: SupersignCLI.config.storage+// )+ let token = try AuthToken.retrieve(deviceInfo: deviceInfo, account: account)- let client = DeveloperServicesClient(loginToken: token.dsToken, deviceInfo: deviceInfo)+ let client = DeveloperServicesClient(+ loginToken: token.dsToken,+ deviceInfo: deviceInfo,+ anisetteProvider: anisetteProvider+ ) let teams: [DeveloperServicesTeam] = try withSyncContinuation { client.send(DeveloperServicesListTeamsRequest(), completion: $0) }@@ -83,6 +116,55 @@ struct DSTeamsListCommand: ParsableCommand { } } +struct DSAnisetteCommand: ParsableCommand {+ private class Provider: RawADIProvider {+ func startProvisioning(+ spim: Data,+ completion: @escaping (Result<(String, Data), Error>) -> Void+ ) {+ print("spim: \(spim.base64EncodedString())")+ completion(.success(("", Data(base64Encoded: Console.prompt("cpim: ")!)!)))+ }++ func endProvisioning(+ session: String,+ routingInfo: UInt64,+ ptm: Data,+ tk: Data,+ completion: @escaping (Result<Data, Error>) -> Void+ ) {+ print("""+ rinfo: \(routingInfo)+ ptm: \(ptm.base64EncodedString())+ tk: \(tk.base64EncodedString())+ """)+ }++ func requestOTP(+ provisioningInfo: Data,+ completion: @escaping (Result<(machineID: Data, otp: Data), Error>) -> Void+ ) {+ print("otp; pinfo: \(provisioningInfo)")+ }+ }++ static let configuration = CommandConfiguration(+ commandName: "anisette",+ abstract: "Test out Anisette data"+ )++ func run() throws {+ let res = try withSyncContinuation {+ try! ADIDataProvider(+ rawProvider: Provider(),+ deviceInfo: .current()!,+ storage: SupersignCLI.config.storage+ ).fetchAnisetteData(completion: $0)+ }+ print(res)+ }+}+ struct DSTeamsCommand: ParsableCommand { static let configuration = CommandConfiguration( commandName: "teams",@@ -98,8 +180,8 @@ struct DSCommand: ParsableCommand { abstract: "Interact with Apple Developer Services", subcommands: [ DSLoginCommand.self,- DSTeamsCommand.self+ DSTeamsCommand.self,+ DSAnisetteCommand.self ] ) }-
SupersignCLISupport/Sources/SupersignCLISupport/ExpressibleByArguments.swift
diff --git a/SupersignCLISupport/Sources/SupersignCLISupport/ExpressibleByArguments.swift b/SupersignCLISupport/Sources/SupersignCLISupport/ExpressibleByArguments.swiftnew file mode 100644index 0000000..4cfbe41--- /dev/null+++ b/SupersignCLISupport/Sources/SupersignCLISupport/ExpressibleByArguments.swift@@ -0,0 +1,27 @@+import ArgumentParser++public protocol ExpressibleByArguments {+ associatedtype Arguments: ParsableArguments+ static func from(_ arguments: Arguments) throws -> Self+}++@propertyWrapper+struct FromArguments<Inner: ExpressibleByArguments>: ParsableArguments {+ @OptionGroup private var arguments: Inner.Arguments+ private var decoded: Inner?++ var wrappedValue: Inner {+ guard let decoded = decoded else {+ fatalError("Value has not yet been parsed")+ }+ return decoded+ }++ private enum CodingKeys: String, CodingKey {+ case arguments+ }++ mutating func validate() throws {+ decoded = try .from(arguments)+ }+}
SupersignCLISupport/Sources/SupersignCLISupport/InstallCommand.swift
diff --git a/SupersignCLISupport/Sources/SupersignCLISupport/InstallCommand.swift b/SupersignCLISupport/Sources/SupersignCLISupport/InstallCommand.swiftindex 12538a4..4577d00 100644--- a/SupersignCLISupport/Sources/SupersignCLISupport/InstallCommand.swift+++ b/SupersignCLISupport/Sources/SupersignCLISupport/InstallCommand.swift@@ -9,9 +9,12 @@ struct InstallCommand: ParsableCommand { abstract: "Install an ipa file to your device" ) - @Option(name: .shortAndLong) var udid: String? @Option(name: .shortAndLong) var account: String?- @Flag var search: ConnectionManager.SearchMode = .all+ @Option(+ name: .shortAndLong,+ help: "Preferred team ID"+ ) var team: String?+ @OptionGroup @FromArguments var client: ConnectionManager.Client @Argument( help: "The path to a custom app/ipa to install"@@ -32,35 +35,10 @@ struct InstallCommand: ParsableCommand { credentials = .password(password) } - print("Waiting for device to be connected...")- var clients: [ConnectionManager.Client]!- let semaphore = DispatchSemaphore(value: 0)- let connDelegate = ConnectionDelegate { currClients in- if let udid = udid {- if let client = currClients.first(where: { $0.udid == udid }) {- clients = [client]- } else {- return- }- } else {- clients = currClients- }- semaphore.signal()- }- try withExtendedLifetime(ConnectionManager(searchMode: search, delegate: connDelegate)) {- semaphore.wait()- }-- let client = Console.choose(- from: clients,- onNoElement: { fatalError() },- multiPrompt: "Choose device",- formatter: { "\($0.deviceName) (\($0.connectionType), udid: \($0.udid))" }- )- print("Installing to device: \(client.deviceName) (udid: \(client.udid))") - let installDelegate = SupersignCLIDelegate(preferredTeam: nil) {+ let semaphore = DispatchSemaphore(value: 0)+ let installDelegate = SupersignCLIDelegate(preferredTeam: team.map(DeveloperServicesTeam.ID.init)) { semaphore.signal() } let installer = IntegratedInstaller(@@ -69,7 +47,7 @@ struct InstallCommand: ParsableCommand { appleID: username, credentials: credentials, configureDevice: false,- signingInfoManager: SupersignCLI.config.signingInfoManager,+ storage: SupersignCLI.config.storage, delegate: installDelegate ) installer.install(app: URL(fileURLWithPath: path))
SupersignCLISupport/Sources/SupersignCLISupport/RunCommand.swift
diff --git a/SupersignCLISupport/Sources/SupersignCLISupport/RunCommand.swift b/SupersignCLISupport/Sources/SupersignCLISupport/RunCommand.swiftnew file mode 100644index 0000000..f1e03c2--- /dev/null+++ b/SupersignCLISupport/Sources/SupersignCLISupport/RunCommand.swift@@ -0,0 +1,45 @@+import Foundation+import Supersign+import SwiftyMobileDevice+import ArgumentParser++struct RunCommand: ParsableCommand {+ static let configuration = CommandConfiguration(+ commandName: "run",+ abstract: "Run an installed app"+ )++ @OptionGroup @FromArguments var connection: ConnectionManager.Client++ @Argument(+ help: "The app to run"+ ) var bundleID: String++ @Argument(+ help: .init(+ "Launch arguments to pass to the app",+ valueName: "arg"+ )+ ) var args: [String] = []++ func run() throws {+ let installProxy = try InstallationProxyClient(device: connection.device, label: "supersign-inst")+ let executable: URL+ do {+ executable = try installProxy.executable(forBundleID: bundleID)+ } catch {+ throw Console.Error("Could not find an installed app with bundle ID '\(bundleID)'")+ }++ print("Launching \(executable.lastPathComponent)...")++ let debugserver = try DebugserverClient(device: connection.device, label: "supersign")+ guard try debugserver.launch(executable: executable, arguments: args) == "OK" else {+ throw Console.Error("Launch failed (!OK)")+ }+ guard try debugserver.send(command: "qLaunchSuccess", arguments: []) == Data("OK".utf8) else {+ throw Console.Error("Launch failed (!qLaunchSuccess)")+ }+ try debugserver.send(command: "D", arguments: [])+ }+}
SupersignCLISupport/Sources/SupersignCLISupport/SuperchargeCommand.swift
diff --git a/SupersignCLISupport/Sources/SupersignCLISupport/SuperchargeCommand.swift b/SupersignCLISupport/Sources/SupersignCLISupport/SuperchargeCommand.swiftindex 2dec395..b1150a9 100644--- a/SupersignCLISupport/Sources/SupersignCLISupport/SuperchargeCommand.swift+++ b/SupersignCLISupport/Sources/SupersignCLISupport/SuperchargeCommand.swift@@ -63,7 +63,7 @@ struct InstallSuperchargeCommand: ParsableCommand { appleID: username, credentials: credentials, configureDevice: true,- signingInfoManager: SupersignCLI.config.signingInfoManager,+ storage: SupersignCLI.config.storage, delegate: installDelegate ) installer.install(app: SupersignCLI.config.superchargeApp)
SupersignCLISupport/Sources/SupersignCLISupport/SupersignCLIDelegate.swift
diff --git a/SupersignCLISupport/Sources/SupersignCLISupport/SupersignCLIDelegate.swift b/SupersignCLISupport/Sources/SupersignCLISupport/SupersignCLIDelegate.swiftindex a7e218b..e0f1737 100644--- a/SupersignCLISupport/Sources/SupersignCLISupport/SupersignCLIDelegate.swift+++ b/SupersignCLISupport/Sources/SupersignCLISupport/SupersignCLIDelegate.swift@@ -28,12 +28,18 @@ final class SupersignCLIDelegate: IntegratedInstallerDelegate, TwoFactorAuthDele } func fetchTeam(fromTeams teams: [DeveloperServicesTeam], completion: @escaping (DeveloperServicesTeam?) -> Void) {+ if let preferredTeam = preferredTeam {+ // Fails if a team with the requested ID isn't found.+ // This is intentional to avoid interactivity.+ return completion(teams.first(where: { $0.id == preferredTeam }))+ }+ let selected = Console.choose( from: teams, onNoElement: { fatalError() },- multiPrompt: "Select a team",+ multiPrompt: "\nSelect a team", formatter: {- "\($0.name) (\($0.id))"+ "\($0.name) (\($0.id.rawValue))" } ) completion(selected)@@ -95,11 +101,18 @@ final class SupersignCLIDelegate: IntegratedInstallerDelegate, TwoFactorAuthDele } } - func installerDidComplete(withResult result: Result<(), Swift.Error>) {+ func installerDidComplete(withResult result: Result<String, Swift.Error>) { print("\n") switch result {- case .success:- print("Complete!")+ case .success(let bundleID):+ print("Successfully installed!")+ if let file = ProcessInfo.processInfo.environment["SUPERSIGN_METADATA_FILE"] {+ do {+ try Data("\(bundleID)\n".utf8).write(to: URL(fileURLWithPath: file))+ } catch {+ print("warning: Failed to write metadata to SUPERSIGN_METADATA_FILE: \(error)")+ }+ } case .failure(let error): print("Failed :(") print("Error: \(error)")
SupersignCLISupport/Sources/SupersignCLISupport/SupersignCommand.swift
diff --git a/SupersignCLISupport/Sources/SupersignCLISupport/SupersignCommand.swift b/SupersignCLISupport/Sources/SupersignCLISupport/SupersignCommand.swiftindex 2d40c39..207d2a0 100644--- a/SupersignCLISupport/Sources/SupersignCLISupport/SupersignCommand.swift+++ b/SupersignCLISupport/Sources/SupersignCLISupport/SupersignCommand.swift@@ -5,11 +5,14 @@ import ArgumentParser public enum SupersignCLI { public struct Configuration { public let superchargeApp: URL- public let signingInfoManager: SigningInfoManager+ public let storage: KeyValueStorage - public init(superchargeApp: URL, signingInfoManager: SigningInfoManager) {+ public init(+ superchargeApp: URL,+ storage: KeyValueStorage+ ) { self.superchargeApp = superchargeApp- self.signingInfoManager = signingInfoManager+ self.storage = storage } } @@ -31,7 +34,9 @@ struct SupersignCommand: ParsableCommand { DSCommand.self, DevicesCommand.self, InstallCommand.self,+ UninstallCommand.self, SuperchargeCommand.self,+ RunCommand.self, ] ) }
SupersignCLISupport/Sources/SupersignCLISupport/UninstallCommand.swift
diff --git a/SupersignCLISupport/Sources/SupersignCLISupport/UninstallCommand.swift b/SupersignCLISupport/Sources/SupersignCLISupport/UninstallCommand.swiftnew file mode 100644index 0000000..6ae9cf7--- /dev/null+++ b/SupersignCLISupport/Sources/SupersignCLISupport/UninstallCommand.swift@@ -0,0 +1,35 @@+import Foundation+import Supersign+import SwiftyMobileDevice+import ArgumentParser++struct UninstallCommand: ParsableCommand {+ static let configuration = CommandConfiguration(+ commandName: "uninstall",+ abstract: "Uninstall an installed app"+ )++ @OptionGroup @FromArguments var connection: ConnectionManager.Client++ @Argument(+ help: "The app to uninstall"+ ) var bundleID: String++ func run() throws {+ let installProxy = try InstallationProxyClient(device: connection.device, label: "supersign-inst")+ let sem = DispatchSemaphore(value: 0)+ var error: Error?+ installProxy.uninstall(bundleID: bundleID, progress: { _ in }) { result in+ if case let .failure(err) = result {+ error = err+ }+ sem.signal()+ }+ sem.wait()+ if let error = error {+ print("Failed: \(error)")+ } else {+ print("Success!")+ }+ }+}