Skip to content

armgit / xtool

Public Imported from GitHub
0

Cross-platform Xcode replacement. Build and deploy iOS apps with SwiftPM on Linux, Windows, macOS.

Migrate Supersign to SPM & support Linux, add NAT/VPN toggle, fix bugs

kabiroberaif9c63acfca71
diff --git a/Supersign/.gitignore b/Supersign/.gitignore
new file mode 100644
index 0000000..bb460e7
--- /dev/null
+++ b/Supersign/.gitignore
@@ -0,0 +1,7 @@
+.DS_Store
+/.build
+/Packages
+/*.xcodeproj
+xcuserdata/
+DerivedData/
+.swiftpm/xcode/package.xcworkspace/contents.xcworkspacedata
diff --git a/Supercharge.xcodeproj/xcshareddata/xcschemes/Supersign.xcscheme b/Supersign/.swiftpm/xcode/xcshareddata/xcschemes/Supersign.xcscheme
similarity index 83%
rename from Supercharge.xcodeproj/xcshareddata/xcschemes/Supersign.xcscheme
rename to Supersign/.swiftpm/xcode/xcshareddata/xcschemes/Supersign.xcscheme
index 3f7cd64..b63fbc3 100644
--- a/Supercharge.xcodeproj/xcshareddata/xcschemes/Supersign.xcscheme
+++ b/Supersign/.swiftpm/xcode/xcshareddata/xcschemes/Supersign.xcscheme
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
- LastUpgradeVersion = "1100"
+ LastUpgradeVersion = "1250"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
@@ -14,10 +14,10 @@
buildForAnalyzing = "YES">
<BuildableReference
BuildableIdentifier = "primary"
- BlueprintIdentifier = "56C6048E234E3EA70008BBB9"
- BuildableName = "Supersign.framework"
+ BlueprintIdentifier = "Supersign"
+ BuildableName = "Supersign"
BlueprintName = "Supersign"
- ReferencedContainer = "container:Supercharge.xcodeproj">
+ ReferencedContainer = "container:">
</BuildableReference>
</BuildActionEntry>
</BuildActionEntries>
@@ -50,10 +50,10 @@
<MacroExpansion>
<BuildableReference
BuildableIdentifier = "primary"
- BlueprintIdentifier = "56C6048E234E3EA70008BBB9"
- BuildableName = "Supersign.framework"
+ BlueprintIdentifier = "Supersign"
+ BuildableName = "Supersign"
BlueprintName = "Supersign"
- ReferencedContainer = "container:Supercharge.xcodeproj">
+ ReferencedContainer = "container:">
</BuildableReference>
</MacroExpansion>
</ProfileAction>
diff --git a/Supersign/Package.resolved b/Supersign/Package.resolved
new file mode 100644
index 0000000..646bc05
--- /dev/null
+++ b/Supersign/Package.resolved
@@ -0,0 +1,61 @@
+{
+ "object": {
+ "pins": [
+ {
+ "package": "async-http-client",
+ "repositoryURL": "https://github.com/swift-server/async-http-client.git",
+ "state": {
+ "branch": null,
+ "revision": "0dda95cffcdf3d96ca551e5701efd1661cf31374",
+ "version": "1.2.5"
+ }
+ },
+ {
+ "package": "swift-log",
+ "repositoryURL": "https://github.com/apple/swift-log.git",
+ "state": {
+ "branch": null,
+ "revision": "5d66f7ba25daf4f94100e7022febf3c75e37a6c7",
+ "version": "1.4.2"
+ }
+ },
+ {
+ "package": "swift-nio",
+ "repositoryURL": "https://github.com/apple/swift-nio.git",
+ "state": {
+ "branch": null,
+ "revision": "21782f3bdc9581148d38d0ccaab6ec952ccda56b",
+ "version": "2.28.0"
+ }
+ },
+ {
+ "package": "swift-nio-extras",
+ "repositoryURL": "https://github.com/apple/swift-nio-extras.git",
+ "state": {
+ "branch": null,
+ "revision": "de1c80ad1fdff1ba772bcef6b392c3ef735f39a6",
+ "version": "1.8.0"
+ }
+ },
+ {
+ "package": "swift-nio-ssl",
+ "repositoryURL": "https://github.com/apple/swift-nio-ssl.git",
+ "state": {
+ "branch": null,
+ "revision": "3d576964a1ace80d2a3f8bab96cab03e5ee074dc",
+ "version": "2.12.0"
+ }
+ },
+ {
+ "package": "swift-nio-transport-services",
+ "repositoryURL": "https://github.com/apple/swift-nio-transport-services.git",
+ "state": {
+ "branch": null,
+ "revision": "657537c2cf1845f8d5201ecc4e48f21f21841128",
+ "version": "1.10.0"
+ }
+ }
+ ]
+ },
+ "version": 1
+}
diff --git a/Supersign/Package.swift b/Supersign/Package.swift
new file mode 100644
index 0000000..09c1916
--- /dev/null
+++ b/Supersign/Package.swift
@@ -0,0 +1,79 @@
+// swift-tools-version:5.3
+
+import PackageDescription
+
+let cSettings: [CSetting] = [
+ .define("_GNU_SOURCE", .when(platforms: [.linux])),
+ // see comment in SupersignLdid
+ .headerSearchPath("../../vendored/include", .when(platforms: [.macOS, .iOS])),
+]
+
+let package = Package(
+ name: "Supersign",
+ platforms: [
+ .iOS("13.0"),
+ .macOS("10.11")
+ ],
+ products: [
+ .library(
+ name: "CSupersign",
+ type: .dynamic,
+ targets: ["CSupersign"]
+ ),
+ .library(
+ name: "Supersign",
+ type: .dynamic,
+ targets: ["Supersign"]
+ ),
+ .executable(
+ name: "SupersignCLI",
+ targets: ["SupersignCLI"]
+ )
+ ],
+ dependencies: [
+ .package(path: "../SuperchargeCore"),
+ .package(path: "../SwiftyMobileDevice"),
+ .package(path: "../USBMuxSim"),
+ .package(path: "../SupersignLdid"),
+ .package(url: "https://github.com/swift-server/async-http-client.git", from: "1.0.0"),
+ ],
+ targets: [
+ .target(
+ name: "CSupersign",
+ dependencies: [
+ .product(name: "OpenSSL", package: "SuperchargeCore")
+ ],
+ cSettings: cSettings
+ ),
+ .target(
+ name: "Supersign",
+ dependencies: [
+ "CSupersign",
+ "SwiftyMobileDevice",
+ .product(name: "PortForwarding", package: "USBMuxSim", condition: .when(platforms: [.iOS])),
+ .product(name: "USBMuxSim", package: "USBMuxSim", condition: .when(platforms: [.iOS])),
+ .product(name: "SignerSupport", package: "SuperchargeCore"),
+ .product(name: "ProtoCodable", package: "SuperchargeCore"),
+ .product(name: "Superutils", package: "SuperchargeCore"),
+ .product(
+ name: "AsyncHTTPClient",
+ package: "async-http-client",
+ condition: .when(platforms: [.linux])
+ )
+ ],
+ cSettings: cSettings
+ ),
+ .target(
+ name: "SupersignCLI",
+ dependencies: [
+ "SwiftyMobileDevice",
+ "Supersign",
+ "SupersignLdid"
+ ],
+ resources: [
+ .copy("Supercharge.ipa")
+ ],
+ cSettings: cSettings
+ )
+ ]
+)
diff --git a/Supersign/README.md b/Supersign/README.md
new file mode 100644
index 0000000..89f7da2
--- /dev/null
+++ b/Supersign/README.md
@@ -0,0 +1,3 @@
+# Supersign
+
+Supersign and related libraries.
diff --git a/Supersign/Model/Mobileprovision/mobileprovision.h b/Supersign/Sources/CSupersign/include/mobileprovision.h
similarity index 100%
rename from Supersign/Model/Mobileprovision/mobileprovision.h
rename to Supersign/Sources/CSupersign/include/mobileprovision.h
diff --git a/Supersign/Model/Mobileprovision/mobileprovision.c b/Supersign/Sources/CSupersign/mobileprovision.c
similarity index 100%
rename from Supersign/Model/Mobileprovision/mobileprovision.c
rename to Supersign/Sources/CSupersign/mobileprovision.c
diff --git a/Supersign/DeveloperServices/App Groups/DeveloperServicesAddAppGroupRequest.swift b/Supersign/Sources/Supersign/DeveloperServices/App Groups/DeveloperServicesAddAppGroupRequest.swift
similarity index 100%
rename from Supersign/DeveloperServices/App Groups/DeveloperServicesAddAppGroupRequest.swift
rename to Supersign/Sources/Supersign/DeveloperServices/App Groups/DeveloperServicesAddAppGroupRequest.swift
diff --git a/Supersign/DeveloperServices/App Groups/DeveloperServicesAppGroup.swift b/Supersign/Sources/Supersign/DeveloperServices/App Groups/DeveloperServicesAppGroup.swift
similarity index 100%
rename from Supersign/DeveloperServices/App Groups/DeveloperServicesAppGroup.swift
rename to Supersign/Sources/Supersign/DeveloperServices/App Groups/DeveloperServicesAppGroup.swift
diff --git a/Supersign/DeveloperServices/App Groups/DeveloperServicesAssignAppGroupRequest.swift b/Supersign/Sources/Supersign/DeveloperServices/App Groups/DeveloperServicesAssignAppGroupRequest.swift
similarity index 100%
rename from Supersign/DeveloperServices/App Groups/DeveloperServicesAssignAppGroupRequest.swift
rename to Supersign/Sources/Supersign/DeveloperServices/App Groups/DeveloperServicesAssignAppGroupRequest.swift
diff --git a/Supersign/DeveloperServices/App Groups/DeveloperServicesAssignAppGroupsOperation.swift b/Supersign/Sources/Supersign/DeveloperServices/App Groups/DeveloperServicesAssignAppGroupsOperation.swift
similarity index 100%
rename from Supersign/DeveloperServices/App Groups/DeveloperServicesAssignAppGroupsOperation.swift
rename to Supersign/Sources/Supersign/DeveloperServices/App Groups/DeveloperServicesAssignAppGroupsOperation.swift
diff --git a/Supersign/DeveloperServices/App Groups/DeveloperServicesListAppGroupsRequest.swift b/Supersign/Sources/Supersign/DeveloperServices/App Groups/DeveloperServicesListAppGroupsRequest.swift
similarity index 100%
rename from Supersign/DeveloperServices/App Groups/DeveloperServicesListAppGroupsRequest.swift
rename to Supersign/Sources/Supersign/DeveloperServices/App Groups/DeveloperServicesListAppGroupsRequest.swift
diff --git a/Supersign/DeveloperServices/App IDs/DeveloperServicesAddAppIDRequest.swift b/Supersign/Sources/Supersign/DeveloperServices/App IDs/DeveloperServicesAddAppIDRequest.swift
similarity index 100%
rename from Supersign/DeveloperServices/App IDs/DeveloperServicesAddAppIDRequest.swift
rename to Supersign/Sources/Supersign/DeveloperServices/App IDs/DeveloperServicesAddAppIDRequest.swift
diff --git a/Supersign/DeveloperServices/App IDs/DeveloperServicesAddAppOperation.swift b/Supersign/Sources/Supersign/DeveloperServices/App IDs/DeveloperServicesAddAppOperation.swift
similarity index 89%
rename from Supersign/DeveloperServices/App IDs/DeveloperServicesAddAppOperation.swift
rename to Supersign/Sources/Supersign/DeveloperServices/App IDs/DeveloperServicesAddAppOperation.swift
index 9acd862..78a1d96 100644
--- a/Supersign/DeveloperServices/App IDs/DeveloperServicesAddAppOperation.swift
+++ b/Supersign/Sources/Supersign/DeveloperServices/App IDs/DeveloperServicesAddAppOperation.swift
@@ -17,19 +17,23 @@ public struct DeveloperServicesAddAppOperation: DeveloperServicesOperation {
public var errorDescription: String? {
switch self {
case .invalidApp(let url):
- return String.localizedStringWithFormat(
- NSLocalizedString(
- "add_app_operation.error.invalid_app", value: "Invalid app: %@", comment: ""
- ), url.path
- )
+ return url.path.withCString {
+ String.localizedStringWithFormat(
+ NSLocalizedString(
+ "add_app_operation.error.invalid_app", value: "Invalid app: %s", comment: ""
+ ), $0
+ )
+ }
case .teamNotFound(let id):
- return String.localizedStringWithFormat(
- NSLocalizedString(
- "add_app_operation.error.team_not_found",
- value: "A team with the ID '%@' could not be found. Please select another team.",
- comment: ""
- ), id.rawValue
- )
+ return id.rawValue.withCString {
+ String.localizedStringWithFormat(
+ NSLocalizedString(
+ "add_app_operation.error.team_not_found",
+ value: "A team with the ID '%s' could not be found. Please select another team.",
+ comment: ""
+ ), $0
+ )
+ }
}
}
}
@@ -88,9 +92,10 @@ public struct DeveloperServicesAddAppOperation: DeveloperServicesOperation {
completion: @escaping (Result<(DeveloperServicesAppID, Entitlements), Swift.Error>) -> Void
) {
let infoURL = app.appendingPathComponent("Info.plist")
- guard let dict = NSDictionary(contentsOf: infoURL),
- let bundleID = dict[kCFBundleIdentifierKey as String] as? String,
- let executable = dict[kCFBundleExecutableKey as String] as? String else {
+ guard let data = try? Data(contentsOf: infoURL),
+ let dict = try? PropertyListSerialization.propertyList(from: data, format: nil) as? [String: Any],
+ let bundleID = dict["CFBundleIdentifier"] as? String,
+ let executable = dict["CFBundleExecutable"] as? String else {
return completion(.failure(Error.invalidApp(app)))
}
let executableURL = app.appendingPathComponent(executable)
diff --git a/Supersign/DeveloperServices/App IDs/DeveloperServicesAppID.swift b/Supersign/Sources/Supersign/DeveloperServices/App IDs/DeveloperServicesAppID.swift
similarity index 100%
rename from Supersign/DeveloperServices/App IDs/DeveloperServicesAppID.swift
rename to Supersign/Sources/Supersign/DeveloperServices/App IDs/DeveloperServicesAppID.swift
diff --git a/Supersign/DeveloperServices/App IDs/DeveloperServicesAppIDRequestApplier.swift b/Supersign/Sources/Supersign/DeveloperServices/App IDs/DeveloperServicesAppIDRequestApplier.swift
similarity index 100%
rename from Supersign/DeveloperServices/App IDs/DeveloperServicesAppIDRequestApplier.swift
rename to Supersign/Sources/Supersign/DeveloperServices/App IDs/DeveloperServicesAppIDRequestApplier.swift
diff --git a/Supersign/DeveloperServices/App IDs/DeveloperServicesDeleteAppIDRequest.swift b/Supersign/Sources/Supersign/DeveloperServices/App IDs/DeveloperServicesDeleteAppIDRequest.swift
similarity index 100%
rename from Supersign/DeveloperServices/App IDs/DeveloperServicesDeleteAppIDRequest.swift
rename to Supersign/Sources/Supersign/DeveloperServices/App IDs/DeveloperServicesDeleteAppIDRequest.swift
diff --git a/Supersign/DeveloperServices/App IDs/DeveloperServicesListAppIDsRequest.swift b/Supersign/Sources/Supersign/DeveloperServices/App IDs/DeveloperServicesListAppIDsRequest.swift
similarity index 100%
rename from Supersign/DeveloperServices/App IDs/DeveloperServicesListAppIDsRequest.swift
rename to Supersign/Sources/Supersign/DeveloperServices/App IDs/DeveloperServicesListAppIDsRequest.swift
diff --git a/Supersign/DeveloperServices/App IDs/DeveloperServicesUpdateAppIDRequest.swift b/Supersign/Sources/Supersign/DeveloperServices/App IDs/DeveloperServicesUpdateAppIDRequest.swift
similarity index 100%
rename from Supersign/DeveloperServices/App IDs/DeveloperServicesUpdateAppIDRequest.swift
rename to Supersign/Sources/Supersign/DeveloperServices/App IDs/DeveloperServicesUpdateAppIDRequest.swift
diff --git a/Supersign/DeveloperServices/App IDs/Entitlements/Entitlement+DeveloperServicesFeature.swift b/Supersign/Sources/Supersign/DeveloperServices/App IDs/Entitlements/Entitlement+DeveloperServicesFeature.swift
similarity index 100%
rename from Supersign/DeveloperServices/App IDs/Entitlements/Entitlement+DeveloperServicesFeature.swift
rename to Supersign/Sources/Supersign/DeveloperServices/App IDs/Entitlements/Entitlement+DeveloperServicesFeature.swift
diff --git a/Supersign/DeveloperServices/App IDs/Entitlements/EntitlementWithTeamOrBundleID.swift b/Supersign/Sources/Supersign/DeveloperServices/App IDs/Entitlements/EntitlementWithTeamOrBundleID.swift
similarity index 100%
rename from Supersign/DeveloperServices/App IDs/Entitlements/EntitlementWithTeamOrBundleID.swift
rename to Supersign/Sources/Supersign/DeveloperServices/App IDs/Entitlements/EntitlementWithTeamOrBundleID.swift
diff --git a/Supersign/DeveloperServices/App IDs/Features/DeveloperServicesFeature.swift b/Supersign/Sources/Supersign/DeveloperServices/App IDs/Features/DeveloperServicesFeature.swift
similarity index 100%
rename from Supersign/DeveloperServices/App IDs/Features/DeveloperServicesFeature.swift
rename to Supersign/Sources/Supersign/DeveloperServices/App IDs/Features/DeveloperServicesFeature.swift
diff --git a/Supersign/DeveloperServices/App IDs/Features/DeveloperServicesFeatureTypes.swift b/Supersign/Sources/Supersign/DeveloperServices/App IDs/Features/DeveloperServicesFeatureTypes.swift
similarity index 100%
rename from Supersign/DeveloperServices/App IDs/Features/DeveloperServicesFeatureTypes.swift
rename to Supersign/Sources/Supersign/DeveloperServices/App IDs/Features/DeveloperServicesFeatureTypes.swift
diff --git a/Supersign/DeveloperServices/App IDs/Features/DeveloperServicesFeatures.swift b/Supersign/Sources/Supersign/DeveloperServices/App IDs/Features/DeveloperServicesFeatures.swift
similarity index 100%
rename from Supersign/DeveloperServices/App IDs/Features/DeveloperServicesFeatures.swift
rename to Supersign/Sources/Supersign/DeveloperServices/App IDs/Features/DeveloperServicesFeatures.swift
diff --git a/Supersign/DeveloperServices/Certificates/DeveloperServicesCSRResponse.swift b/Supersign/Sources/Supersign/DeveloperServices/Certificates/DeveloperServicesCSRResponse.swift
similarity index 100%
rename from Supersign/DeveloperServices/Certificates/DeveloperServicesCSRResponse.swift
rename to Supersign/Sources/Supersign/DeveloperServices/Certificates/DeveloperServicesCSRResponse.swift
diff --git a/Supersign/DeveloperServices/Certificates/DeveloperServicesCertificate.swift b/Supersign/Sources/Supersign/DeveloperServices/Certificates/DeveloperServicesCertificate.swift
similarity index 100%
rename from Supersign/DeveloperServices/Certificates/DeveloperServicesCertificate.swift
rename to Supersign/Sources/Supersign/DeveloperServices/Certificates/DeveloperServicesCertificate.swift
diff --git a/Supersign/DeveloperServices/Certificates/DeveloperServicesFetchCertificateOperation.swift b/Supersign/Sources/Supersign/DeveloperServices/Certificates/DeveloperServicesFetchCertificateOperation.swift
similarity index 100%
rename from Supersign/DeveloperServices/Certificates/DeveloperServicesFetchCertificateOperation.swift
rename to Supersign/Sources/Supersign/DeveloperServices/Certificates/DeveloperServicesFetchCertificateOperation.swift
diff --git a/Supersign/DeveloperServices/Certificates/DeveloperServicesListCertificatesRequest.swift b/Supersign/Sources/Supersign/DeveloperServices/Certificates/DeveloperServicesListCertificatesRequest.swift
similarity index 100%
rename from Supersign/DeveloperServices/Certificates/DeveloperServicesListCertificatesRequest.swift
rename to Supersign/Sources/Supersign/DeveloperServices/Certificates/DeveloperServicesListCertificatesRequest.swift
diff --git a/Supersign/DeveloperServices/Certificates/DeveloperServicesRevokeCertificateRequest.swift b/Supersign/Sources/Supersign/DeveloperServices/Certificates/DeveloperServicesRevokeCertificateRequest.swift
similarity index 100%
rename from Supersign/DeveloperServices/Certificates/DeveloperServicesRevokeCertificateRequest.swift
rename to Supersign/Sources/Supersign/DeveloperServices/Certificates/DeveloperServicesRevokeCertificateRequest.swift
diff --git a/Supersign/DeveloperServices/Certificates/DeveloperServicesSubmitCSRRequest.swift b/Supersign/Sources/Supersign/DeveloperServices/Certificates/DeveloperServicesSubmitCSRRequest.swift
similarity index 100%
rename from Supersign/DeveloperServices/Certificates/DeveloperServicesSubmitCSRRequest.swift
rename to Supersign/Sources/Supersign/DeveloperServices/Certificates/DeveloperServicesSubmitCSRRequest.swift
diff --git a/Supersign/DeveloperServices/Developer/DeveloperServicesViewDeveloperRequest.swift b/Supersign/Sources/Supersign/DeveloperServices/Developer/DeveloperServicesViewDeveloperRequest.swift
similarity index 100%
rename from Supersign/DeveloperServices/Developer/DeveloperServicesViewDeveloperRequest.swift
rename to Supersign/Sources/Supersign/DeveloperServices/Developer/DeveloperServicesViewDeveloperRequest.swift
diff --git a/Supersign/DeveloperServices/DeveloperServicesAPIVersion.swift b/Supersign/Sources/Supersign/DeveloperServices/DeveloperServicesAPIVersion.swift
similarity index 84%
rename from Supersign/DeveloperServices/DeveloperServicesAPIVersion.swift
rename to Supersign/Sources/Supersign/DeveloperServices/DeveloperServicesAPIVersion.swift
index 246b53f..051facd 100644
--- a/Supersign/DeveloperServices/DeveloperServicesAPIVersion.swift
+++ b/Supersign/Sources/Supersign/DeveloperServices/DeveloperServicesAPIVersion.swift
@@ -7,6 +7,7 @@
//
import Foundation
+import Superutils
public protocol DeveloperServicesAPIVersion {
func url(forAction action: String) -> URL?
@@ -23,24 +24,28 @@ public struct DeveloperServicesAPIVersionOld: DeveloperServicesAPIVersion {
public let reason: String?
public var errorDescription: String? {
- if let reason = reason {
- return String.localizedStringWithFormat(
- NSLocalizedString(
- "developer_services_api.old.error.reason_and_code",
- value: "%@ (%@)",
- comment: "First reason, then code"
- ),
- reason, "\(code)"
- )
- } else {
- return String.localizedStringWithFormat(
- NSLocalizedString(
- "developer_services_api.old.error.only_code",
- value: "An unknown error occurred (%@)",
- comment: ""
- ),
- "\(code)"
- )
+ return "\(code)".withCString { codeC in
+ if let reason = reason {
+ return reason.withCString { reasonC in
+ String.localizedStringWithFormat(
+ NSLocalizedString(
+ "developer_services_api.old.error.reason_and_code",
+ value: "%s (%s)",
+ comment: "First reason, then code"
+ ),
+ reasonC, codeC
+ )
+ }
+ } else {
+ return String.localizedStringWithFormat(
+ NSLocalizedString(
+ "developer_services_api.old.error.only_code",
+ value: "An unknown error occurred (%s)",
+ comment: ""
+ ),
+ codeC
+ )
+ }
}
}
}
diff --git a/Supersign/Sources/Supersign/DeveloperServices/DeveloperServicesClient.swift b/Supersign/Sources/Supersign/DeveloperServices/DeveloperServicesClient.swift
new file mode 100644
index 0000000..793c1ca
--- /dev/null
+++ b/Supersign/Sources/Supersign/DeveloperServices/DeveloperServicesClient.swift
@@ -0,0 +1,138 @@
+//
+// DeveloperServicesClient.swift
+// Supercharge
+//
+// Created by Kabir Oberai on 24/07/19.
+// Copyright © 2019 Kabir Oberai. All rights reserved.
+//
+
+import Foundation
+
+public final class DeveloperServicesClient {
+
+ public enum Error: LocalizedError {
+ case noData
+ case malformedRequest
+ case apiError(code: Int, reason: String?)
+
+ public var errorDescription: String? {
+ switch self {
+ case .noData:
+ return NSLocalizedString(
+ "developer_services_client.error.no_data", value: "No data", comment: ""
+ )
+ case .malformedRequest:
+ return NSLocalizedString(
+ "developer_services_client.error.malformed_request", value: "Malformed request", comment: ""
+ )
+ case .apiError(let code, let reason?):
+ return reason.withCString { reasonC in
+ "\(code)".withCString { codeC in
+ String.localizedStringWithFormat(
+ NSLocalizedString(
+ "developer_services_client.error.sign_in_error.reason_and_code",
+ value: "%s (%s)",
+ comment: "First reason, then code"
+ ),
+ reasonC, codeC
+ )
+ }
+ }
+ case .apiError(let code, _):
+ return "\(code)".withCString {
+ String.localizedStringWithFormat(
+ NSLocalizedString(
+ "developer_services_client.error.sign_in_error.only_code",
+ value: "An unknown error occurred (%s)",
+ comment: ""
+ ),
+ $0
+ )
+ }
+ }
+ }
+ }
+
+ public let loginToken: DeveloperServicesLoginToken
+ public let deviceInfo: DeviceInfo
+ public let anisetteDataProvider: AnisetteDataProvider
+ private let httpClient: HTTPClientProtocol
+
+ public init(
+ loginToken: DeveloperServicesLoginToken,
+ deviceInfo: DeviceInfo,
+ httpFactory: HTTPClientFactory.Type = defaultHTTPClientFactory,
+ customAnisetteDataProvider: AnisetteDataProvider? = nil
+ ) {
+ self.loginToken = loginToken
+ self.deviceInfo = deviceInfo
+ self.anisetteDataProvider = customAnisetteDataProvider
+ ?? SupersetteDataProvider(deviceInfo: deviceInfo)
+ self.httpClient = httpFactory.shared.makeClient()
+ }
+
+ private func send<R: DeveloperServicesRequest>(
+ _ request: R,
+ anisetteData: AnisetteData,
+ completion: @escaping (Result<R.Value, Swift.Error>) -> Void
+ ) {
+ guard let url = request.apiVersion.url(forAction: request.action) else {
+ return completion(.failure(Error.malformedRequest))
+ }
+
+ var httpRequest = HTTPRequest(url: url, method: "POST")
+ let acceptedLanguages = Locale.preferredLanguages.joined(separator: ", ")
+
+ httpRequest.headers["Accept-Language"] = acceptedLanguages
+ httpRequest.headers["Accept"] = request.apiVersion.accept
+ httpRequest.headers["Content-Type"] = request.apiVersion.contentType
+ httpRequest.headers["User-Agent"] = "Xcode"
+ request.methodOverride.map { httpRequest.headers["X-HTTP-Method-Override"] = $0 }
+
+ httpRequest.headers[DeviceInfo.xcodeVersionKey] = DeviceInfo.xcodeVersion
+ httpRequest.headers[DeviceInfo.clientInfoKey] = deviceInfo.clientInfo.clientString
+ httpRequest.headers[DeviceInfo.deviceIDKey] = deviceInfo.deviceID
+
+ httpRequest.headers["X-Apple-I-Identity-Id"] = loginToken.adsid
+ httpRequest.headers["X-Apple-App-Info"] = AppTokenKey.xcode.rawValue
+ httpRequest.headers["X-Apple-GS-Token"] = loginToken.token
+
+ anisetteData.dictionary.forEach { httpRequest.headers[$0] = $1 }
+
+ do {
+ httpRequest.body = try .buffer(request.apiVersion.body(withParameters: request.parameters))
+ } catch {
+ return completion(.failure(error))
+ }
+
+ request.configure(urlRequest: &httpRequest)
+
+ httpClient.makeRequest(httpRequest) { result in
+ let decoded: R.Response
+ do {
+ let resp = try result.get()
+ // we don't throw if data is nil because sometimes no data is
+ // okay (eg in the case of EmptyResponse)
+ let data = resp.body ?? Data()
+
+// String(data: data, encoding: .utf8).map { print("\(url): \($0)") }
+
+ decoded = try request.apiVersion.decode(response: data)
+ } catch {
+ return completion(.failure(error))
+ }
+ request.parse(decoded, completion: completion)
+ }
+ }
+
+ public func send<R: DeveloperServicesRequest>(
+ _ request: R,
+ completion: @escaping (Result<R.Value, Swift.Error>) -> Void
+ ) {
+ anisetteDataProvider.fetchAnisetteData { result in
+ guard let anisetteData = result.get(withErrorHandler: completion) else { return }
+ self.send(request, anisetteData: anisetteData, completion: completion)
+ }
+ }
+
+}
diff --git a/Supersign/DeveloperServices/DeveloperServicesLoginManager.swift b/Supersign/Sources/Supersign/DeveloperServices/DeveloperServicesLoginManager.swift
similarity index 100%
rename from Supersign/DeveloperServices/DeveloperServicesLoginManager.swift
rename to Supersign/Sources/Supersign/DeveloperServices/DeveloperServicesLoginManager.swift
diff --git a/Supersign/DeveloperServices/DeveloperServicesOperation.swift b/Supersign/Sources/Supersign/DeveloperServices/DeveloperServicesOperation.swift
similarity index 100%
rename from Supersign/DeveloperServices/DeveloperServicesOperation.swift
rename to Supersign/Sources/Supersign/DeveloperServices/DeveloperServicesOperation.swift
diff --git a/Supersign/DeveloperServices/DeveloperServicesPlatformRequest.swift b/Supersign/Sources/Supersign/DeveloperServices/DeveloperServicesPlatformRequest.swift
similarity index 100%
rename from Supersign/DeveloperServices/DeveloperServicesPlatformRequest.swift
rename to Supersign/Sources/Supersign/DeveloperServices/DeveloperServicesPlatformRequest.swift
diff --git a/Supersign/DeveloperServices/DeveloperServicesProvisioningOperation.swift b/Supersign/Sources/Supersign/DeveloperServices/DeveloperServicesProvisioningOperation.swift
similarity index 100%
rename from Supersign/DeveloperServices/DeveloperServicesProvisioningOperation.swift
rename to Supersign/Sources/Supersign/DeveloperServices/DeveloperServicesProvisioningOperation.swift
diff --git a/Supersign/DeveloperServices/DeveloperServicesRequest.swift b/Supersign/Sources/Supersign/DeveloperServices/DeveloperServicesRequest.swift
similarity index 90%
rename from Supersign/DeveloperServices/DeveloperServicesRequest.swift
rename to Supersign/Sources/Supersign/DeveloperServices/DeveloperServicesRequest.swift
index e95d0f2..5ff9d44 100644
--- a/Supersign/DeveloperServices/DeveloperServicesRequest.swift
+++ b/Supersign/Sources/Supersign/DeveloperServices/DeveloperServicesRequest.swift
@@ -21,7 +21,7 @@ public protocol DeveloperServicesRequest {
var action: String { get }
var parameters: [String: Any] { get }
- func configure(urlRequest: inout URLRequest)
+ func configure(urlRequest: inout HTTPRequest)
func parse(_ response: Response, completion: @escaping (Result<Value, Error>) -> Void)
}
@@ -29,7 +29,7 @@ public protocol DeveloperServicesRequest {
public extension DeveloperServicesRequest {
var apiVersion: DeveloperServicesAPIVersion { DeveloperServicesAPIVersionOld() }
var methodOverride: String? { nil }
- func configure(urlRequest: inout URLRequest) {}
+ func configure(urlRequest: inout HTTPRequest) {}
}
public extension DeveloperServicesRequest where Response == Value {
diff --git a/Supersign/DeveloperServices/Devices/DeveloperServicesAddDeviceRequest.swift b/Supersign/Sources/Supersign/DeveloperServices/Devices/DeveloperServicesAddDeviceRequest.swift
similarity index 100%
rename from Supersign/DeveloperServices/Devices/DeveloperServicesAddDeviceRequest.swift
rename to Supersign/Sources/Supersign/DeveloperServices/Devices/DeveloperServicesAddDeviceRequest.swift
diff --git a/Supersign/DeveloperServices/Devices/DeveloperServicesDevice.swift b/Supersign/Sources/Supersign/DeveloperServices/Devices/DeveloperServicesDevice.swift
similarity index 100%
rename from Supersign/DeveloperServices/Devices/DeveloperServicesDevice.swift
rename to Supersign/Sources/Supersign/DeveloperServices/Devices/DeveloperServicesDevice.swift
diff --git a/Supersign/DeveloperServices/Devices/DeveloperServicesFetchDeviceOperation.swift b/Supersign/Sources/Supersign/DeveloperServices/Devices/DeveloperServicesFetchDeviceOperation.swift
similarity index 100%
rename from Supersign/DeveloperServices/Devices/DeveloperServicesFetchDeviceOperation.swift
rename to Supersign/Sources/Supersign/DeveloperServices/Devices/DeveloperServicesFetchDeviceOperation.swift
diff --git a/Supersign/DeveloperServices/Devices/DeveloperServicesListDevicesRequest.swift b/Supersign/Sources/Supersign/DeveloperServices/Devices/DeveloperServicesListDevicesRequest.swift
similarity index 100%
rename from Supersign/DeveloperServices/Devices/DeveloperServicesListDevicesRequest.swift
rename to Supersign/Sources/Supersign/DeveloperServices/Devices/DeveloperServicesListDevicesRequest.swift
diff --git a/Supersign/DeveloperServices/Profiles/DeveloperServicesDeleteProfileRequest.swift b/Supersign/Sources/Supersign/DeveloperServices/Profiles/DeveloperServicesDeleteProfileRequest.swift
similarity index 100%
rename from Supersign/DeveloperServices/Profiles/DeveloperServicesDeleteProfileRequest.swift
rename to Supersign/Sources/Supersign/DeveloperServices/Profiles/DeveloperServicesDeleteProfileRequest.swift
diff --git a/Supersign/DeveloperServices/Profiles/DeveloperServicesFetchProfileOperation.swift b/Supersign/Sources/Supersign/DeveloperServices/Profiles/DeveloperServicesFetchProfileOperation.swift
similarity index 99%
rename from Supersign/DeveloperServices/Profiles/DeveloperServicesFetchProfileOperation.swift
rename to Supersign/Sources/Supersign/DeveloperServices/Profiles/DeveloperServicesFetchProfileOperation.swift
index 773bacc..7dbfec0 100644
--- a/Supersign/DeveloperServices/Profiles/DeveloperServicesFetchProfileOperation.swift
+++ b/Supersign/Sources/Supersign/DeveloperServices/Profiles/DeveloperServicesFetchProfileOperation.swift
@@ -7,6 +7,7 @@
//
import Foundation
+import Superutils
public struct DeveloperServicesFetchProfileOperation: DeveloperServicesOperation {
diff --git a/Supersign/DeveloperServices/Profiles/DeveloperServicesGetProfileRequest.swift b/Supersign/Sources/Supersign/DeveloperServices/Profiles/DeveloperServicesGetProfileRequest.swift
similarity index 100%
rename from Supersign/DeveloperServices/Profiles/DeveloperServicesGetProfileRequest.swift
rename to Supersign/Sources/Supersign/DeveloperServices/Profiles/DeveloperServicesGetProfileRequest.swift
diff --git a/Supersign/DeveloperServices/Profiles/DeveloperServicesListProfilesRequest.swift b/Supersign/Sources/Supersign/DeveloperServices/Profiles/DeveloperServicesListProfilesRequest.swift
similarity index 100%
rename from Supersign/DeveloperServices/Profiles/DeveloperServicesListProfilesRequest.swift
rename to Supersign/Sources/Supersign/DeveloperServices/Profiles/DeveloperServicesListProfilesRequest.swift
diff --git a/Supersign/DeveloperServices/Profiles/DeveloperServicesProfile.swift b/Supersign/Sources/Supersign/DeveloperServices/Profiles/DeveloperServicesProfile.swift
similarity index 100%
rename from Supersign/DeveloperServices/Profiles/DeveloperServicesProfile.swift
rename to Supersign/Sources/Supersign/DeveloperServices/Profiles/DeveloperServicesProfile.swift
diff --git a/Supersign/DeveloperServices/Teams/DeveloperServicesListTeamsRequest.swift b/Supersign/Sources/Supersign/DeveloperServices/Teams/DeveloperServicesListTeamsRequest.swift
similarity index 100%
rename from Supersign/DeveloperServices/Teams/DeveloperServicesListTeamsRequest.swift
rename to Supersign/Sources/Supersign/DeveloperServices/Teams/DeveloperServicesListTeamsRequest.swift
diff --git a/Supersign/DeveloperServices/Teams/DeveloperServicesTeam.swift b/Supersign/Sources/Supersign/DeveloperServices/Teams/DeveloperServicesTeam.swift
similarity index 100%
rename from Supersign/DeveloperServices/Teams/DeveloperServicesTeam.swift
rename to Supersign/Sources/Supersign/DeveloperServices/Teams/DeveloperServicesTeam.swift
diff --git a/Supersign/GrandSlam/Anisette/AnisetteData.swift b/Supersign/Sources/Supersign/GrandSlam/Anisette/AnisetteData.swift
similarity index 100%
rename from Supersign/GrandSlam/Anisette/AnisetteData.swift
rename to Supersign/Sources/Supersign/GrandSlam/Anisette/AnisetteData.swift
diff --git a/Supersign/GrandSlam/Anisette/AnisetteDataProvider.swift b/Supersign/Sources/Supersign/GrandSlam/Anisette/AnisetteDataProvider.swift
similarity index 100%
rename from Supersign/GrandSlam/Anisette/AnisetteDataProvider.swift
rename to Supersign/Sources/Supersign/GrandSlam/Anisette/AnisetteDataProvider.swift
diff --git a/Supersign/GrandSlam/Anisette/DeviceInfo+Fetching.swift b/Supersign/Sources/Supersign/GrandSlam/Anisette/DeviceInfo+Fetching.swift
similarity index 87%
rename from Supersign/GrandSlam/Anisette/DeviceInfo+Fetching.swift
rename to Supersign/Sources/Supersign/GrandSlam/Anisette/DeviceInfo+Fetching.swift
index 3e600a6..8fa44a7 100644
--- a/Supersign/GrandSlam/Anisette/DeviceInfo+Fetching.swift
+++ b/Supersign/Sources/Supersign/GrandSlam/Anisette/DeviceInfo+Fetching.swift
@@ -83,4 +83,19 @@ extension DeviceInfo {
}
}
+#elseif os(Linux) || os(Windows)
+extension DeviceInfo {
+ public static func current() -> DeviceInfo? {
+ return DeviceInfo(
+ deviceID: "99B5D9D4-B068-5CEE-A799-5EBB5B0894A6",
+ romAddress: "94f6a300e9a0",
+ mlbSerialNumber: "C02520301W0GF2D1U",
+ serialNumber: "C02PQKRJG8WP",
+ modelID: "MacBookPro11,5"
+ )
+ }
+}
#endif
+
+#warning("Figure out DeviceInfo.current() on Windows/Linux")
+// (see above)
diff --git a/Supersign/GrandSlam/Anisette/DeviceInfo.swift b/Supersign/Sources/Supersign/GrandSlam/Anisette/DeviceInfo.swift
similarity index 100%
rename from Supersign/GrandSlam/Anisette/DeviceInfo.swift
rename to Supersign/Sources/Supersign/GrandSlam/Anisette/DeviceInfo.swift
diff --git a/Supersign/GrandSlam/Anisette/LocalAnisetteDataProviders.swift b/Supersign/Sources/Supersign/GrandSlam/Anisette/LocalAnisetteDataProviders.swift
similarity index 99%
rename from Supersign/GrandSlam/Anisette/LocalAnisetteDataProviders.swift
rename to Supersign/Sources/Supersign/GrandSlam/Anisette/LocalAnisetteDataProviders.swift
index cabae3c..200eacb 100644
--- a/Supersign/GrandSlam/Anisette/LocalAnisetteDataProviders.swift
+++ b/Supersign/Sources/Supersign/GrandSlam/Anisette/LocalAnisetteDataProviders.swift
@@ -6,6 +6,8 @@
// Copyright © 2020 Kabir Oberai. All rights reserved.
//
+#if false
+
import Foundation
/// Creates a socket connected to `ip` on `port`.
@@ -248,3 +250,5 @@ public class TCPAnisetteDataProvider: AnisetteDataProvider {
}
}
+
+#endif
diff --git a/Supersign/GrandSlam/Anisette/Supersette/SupersetteDataProvider.swift b/Supersign/Sources/Supersign/GrandSlam/Anisette/Supersette/SupersetteDataProvider.swift
similarity index 70%
rename from Supersign/GrandSlam/Anisette/Supersette/SupersetteDataProvider.swift
rename to Supersign/Sources/Supersign/GrandSlam/Anisette/Supersette/SupersetteDataProvider.swift
index f63d18d..51ad0c9 100644
--- a/Supersign/GrandSlam/Anisette/Supersette/SupersetteDataProvider.swift
+++ b/Supersign/Sources/Supersign/GrandSlam/Anisette/Supersette/SupersetteDataProvider.swift
@@ -21,9 +21,11 @@ public class SupersetteDataProvider: AnisetteDataProvider {
}
public let deviceInfo: DeviceInfo
+ private let httpClient: HTTPClientProtocol
- public init(deviceInfo: DeviceInfo) {
+ public init(deviceInfo: DeviceInfo, httpFactory: HTTPClientFactory.Type = defaultHTTPClientFactory) {
self.deviceInfo = deviceInfo
+ self.httpClient = httpFactory.shared.makeClient()
}
private struct AnisetteRequestBody: Encodable {
@@ -40,23 +42,24 @@ public class SupersetteDataProvider: AnisetteDataProvider {
public func fetchAnisetteData(completion: @escaping (Result<AnisetteData, Swift.Error>) -> Void) {
let clientTime = Date()
- var request = URLRequest(url: Self.gateway)
- request.httpMethod = "POST"
- request.addValue("application/json", forHTTPHeaderField: "Content-Type")
- request.addValue("application/json", forHTTPHeaderField: "Accept")
- request.addValue("BF95B548-3C87-4BBD-8B96-534421368416", forHTTPHeaderField: "Superpass")
+ var request = HTTPRequest(url: Self.gateway, method: "POST")
+ request.headers = [
+ "Content-Type": "application/json",
+ "Accept": "application/json",
+ "Superpass": "BF95B548-3C87-4BBD-8B96-534421368416"
+ ]
do {
- request.httpBody = try Self.encoder.encode(AnisetteRequestBody(
+ request.body = try .buffer(Self.encoder.encode(AnisetteRequestBody(
deviceID: deviceInfo.deviceID,
clientInfo: deviceInfo.clientInfo.clientString
- ))
+ )))
} catch {
return completion(.failure(error))
}
- URLSession.shared.dataTask(with: request) { data, _, error in
+ httpClient.makeRequest(request) { result in
completion(Result {
- if let error = error { throw error }
- let data = try data.orThrow(Error.invalidAnisetteData)
+ let resp = try result.get()
+ let data = try resp.body.orThrow(Error.invalidAnisetteData)
let anisetteResponse = try Self.decoder.decode(AnisetteResponse.self, from: data)
return AnisetteData(
clientTime: clientTime,
@@ -66,7 +69,7 @@ public class SupersetteDataProvider: AnisetteDataProvider {
oneTimePassword: anisetteResponse.oneTimePassword
)
})
- }.resume()
+ }
}
}
diff --git a/Supersign/GrandSlam/Crypto/AppTokens.swift b/Supersign/Sources/Supersign/GrandSlam/Crypto/AppTokens.swift
similarity index 98%
rename from Supersign/GrandSlam/Crypto/AppTokens.swift
rename to Supersign/Sources/Supersign/GrandSlam/Crypto/AppTokens.swift
index 25d02ec..69df654 100644
--- a/Supersign/GrandSlam/Crypto/AppTokens.swift
+++ b/Supersign/Sources/Supersign/GrandSlam/Crypto/AppTokens.swift
@@ -7,6 +7,7 @@
//
import Foundation
+import CSupersign
enum AppTokens {
diff --git a/Supersign/GrandSlam/Crypto/SRPClient.swift b/Supersign/Sources/Supersign/GrandSlam/Crypto/SRPClient.swift
similarity index 99%
rename from Supersign/GrandSlam/Crypto/SRPClient.swift
rename to Supersign/Sources/Supersign/GrandSlam/Crypto/SRPClient.swift
index 8972554..5379569 100644
--- a/Supersign/GrandSlam/Crypto/SRPClient.swift
+++ b/Supersign/Sources/Supersign/GrandSlam/Crypto/SRPClient.swift
@@ -7,6 +7,7 @@
//
import Foundation
+import CSupersign
final class SRPClient {
diff --git a/Supersign/GrandSlam/GrandSlamClient.swift b/Supersign/Sources/Supersign/GrandSlam/GrandSlamClient.swift
similarity index 70%
rename from Supersign/GrandSlam/GrandSlamClient.swift
rename to Supersign/Sources/Supersign/GrandSlam/GrandSlamClient.swift
index d529400..2a784d1 100644
--- a/Supersign/GrandSlam/GrandSlamClient.swift
+++ b/Supersign/Sources/Supersign/GrandSlam/GrandSlamClient.swift
@@ -16,14 +16,17 @@ class GrandSlamClient {
let deviceInfo: DeviceInfo
let anisetteDataProvider: AnisetteDataProvider
+ private let httpClient: HTTPClientProtocol
init(
deviceInfo: DeviceInfo,
+ httpFactory: HTTPClientFactory.Type = defaultHTTPClientFactory,
customAnisetteDataProvider: AnisetteDataProvider? = nil
) {
self.deviceInfo = deviceInfo
self.anisetteDataProvider = customAnisetteDataProvider
?? SupersetteDataProvider(deviceInfo: deviceInfo)
- self.lookupManager = .init(deviceInfo: deviceInfo)
+ self.lookupManager = .init(deviceInfo: deviceInfo, httpFactory: httpFactory)
+ self.httpClient = httpFactory.shared.makeClient()
}
private func send<R: GrandSlamRequest>(
@@ -32,35 +35,32 @@ class GrandSlamClient {
url: URL,
completion: @escaping (Result<R.Decoder.Value, Swift.Error>) -> Void
) {
- var urlRequest = URLRequest(url: url)
- urlRequest.setValue("text/x-xml-plist", forHTTPHeaderField: "Content-Type")
- urlRequest.setValue(deviceInfo.clientInfo.clientString, forHTTPHeaderField: DeviceInfo.clientInfoKey)
-
let method = request.method(deviceInfo: deviceInfo, anisetteData: anisetteData)
- urlRequest.httpMethod = method.name
+ var httpRequest = HTTPRequest(url: url, method: method.name)
+ httpRequest.headers = [
+ "Content-Type": "text/x-xml-plist",
+ DeviceInfo.clientInfoKey: deviceInfo.clientInfo.clientString
+ ]
switch method {
case .get:
break
case .post(let body):
do {
- urlRequest.httpBody = try PropertyListSerialization.data(
+ httpRequest.body = try .buffer(PropertyListSerialization.data(
fromPropertyList: body, format: .xml, options: 0
- )
+ ))
} catch {
return completion(.failure(error))
}
}
- request.configure(request: &urlRequest, deviceInfo: deviceInfo, anisetteData: anisetteData)
+ request.configure(request: &httpRequest, deviceInfo: deviceInfo, anisetteData: anisetteData)
- URLSession.shared.dataTask(with: urlRequest) { data, _, error in
-// print(response.map(String.init(describing:)) ?? "NO RESPONSE")
- if let error = error {
- return completion(.failure(error))
- }
+ httpClient.makeRequest(httpRequest) { result in
+ guard let resp = result.get(withErrorHandler: completion) else { return }
completion(Result {
- try R.Decoder.decode(data: data ?? .init())
+ try R.Decoder.decode(data: resp.body ?? .init())
})
- }.resume()
+ }
}
private func send<R: GrandSlamRequest>(
diff --git a/Supersign/GrandSlam/Lookup/GrandSlamEndpoints.swift b/Supersign/Sources/Supersign/GrandSlam/Lookup/GrandSlamEndpoints.swift
similarity index 100%
rename from Supersign/GrandSlam/Lookup/GrandSlamEndpoints.swift
rename to Supersign/Sources/Supersign/GrandSlam/Lookup/GrandSlamEndpoints.swift
diff --git a/Supersign/GrandSlam/Lookup/GrandSlamLookupManager.swift b/Supersign/Sources/Supersign/GrandSlam/Lookup/GrandSlamLookupManager.swift
similarity index 64%
rename from Supersign/GrandSlam/Lookup/GrandSlamLookupManager.swift
rename to Supersign/Sources/Supersign/GrandSlam/Lookup/GrandSlamLookupManager.swift
index 3ba0713..13ae994 100644
--- a/Supersign/GrandSlam/Lookup/GrandSlamLookupManager.swift
+++ b/Supersign/Sources/Supersign/GrandSlam/Lookup/GrandSlamLookupManager.swift
@@ -19,9 +19,11 @@ class GrandSlamLookupManager {
private let decoder = PropertyListDecoder()
private var endpoints: GrandSlamEndpoints?
+ let httpClient: HTTPClientProtocol
let deviceInfo: DeviceInfo
- init(deviceInfo: DeviceInfo) {
+ init(deviceInfo: DeviceInfo, httpFactory: HTTPClientFactory.Type = defaultHTTPClientFactory) {
self.deviceInfo = deviceInfo
+ self.httpClient = httpFactory.shared.makeClient()
}
private func performLookup(completion: @escaping (Result<GrandSlamEndpoints, Error>) -> Void) {
@@ -33,23 +35,22 @@ class GrandSlamLookupManager {
"X-MMe-Country" = IN;
"X-Mme-Device-Id" = "[REDACTED]";
} */
- var request = URLRequest(url: Self.lookupURL)
- request.setValue(deviceInfo.clientInfo.clientString, forHTTPHeaderField: DeviceInfo.clientInfoKey)
- request.setValue(deviceInfo.deviceID, forHTTPHeaderField: DeviceInfo.deviceIDKey)
- request.setValue(Locale.current.regionCode, forHTTPHeaderField: "X-MMe-Country")
- request.setValue(Locale.current.identifier, forHTTPHeaderField: AnisetteData.iLocaleKey)
- request.setValue(TimeZone.current.identifier, forHTTPHeaderField: AnisetteData.timeZoneKey)
- request.setValue("\(TimeZone.current.secondsFromGMT())", forHTTPHeaderField: "X-Apple-I-TimeZone-Offset")
-
- URLSession.shared.dataTask(with: request) { data, _, error in
- if let error = error {
- return completion(.failure(error))
- }
+ var request = HTTPRequest(url: Self.lookupURL)
+ request.headers = [
+ DeviceInfo.clientInfoKey: deviceInfo.clientInfo.clientString,
+ DeviceInfo.deviceIDKey: deviceInfo.deviceID,
+ AnisetteData.iLocaleKey: Locale.current.identifier,
+ AnisetteData.timeZoneKey: TimeZone.current.identifier,
+ "X-Apple-I-TimeZone-Offset": "\(TimeZone.current.secondsFromGMT())"
+ ]
+ request.headers["X-MMe-Country"] = Locale.current.regionCode
+ httpClient.makeRequest(request) { result in
+ guard let resp = result.get(withErrorHandler: completion) else { return }
completion(Result {
- try self.decoder.decode(Response.self, from: data ?? .init()).urls
+ try self.decoder.decode(Response.self, from: resp.body ?? .init()).urls
})
- }.resume()
+ }
}
private func fetchEndpoints(completion: @escaping (Result<GrandSlamEndpoints, Error>) -> Void) {
diff --git a/Supersign/GrandSlam/Model/GrandSlamAuthEndpoint.swift b/Supersign/Sources/Supersign/GrandSlam/Model/GrandSlamAuthEndpoint.swift
similarity index 100%
rename from Supersign/GrandSlam/Model/GrandSlamAuthEndpoint.swift
rename to Supersign/Sources/Supersign/GrandSlam/Model/GrandSlamAuthEndpoint.swift
diff --git a/Supersign/GrandSlam/Model/GrandSlamAuthProtocol.swift b/Supersign/Sources/Supersign/GrandSlam/Model/GrandSlamAuthProtocol.swift
similarity index 100%
rename from Supersign/GrandSlam/Model/GrandSlamAuthProtocol.swift
rename to Supersign/Sources/Supersign/GrandSlam/Model/GrandSlamAuthProtocol.swift
diff --git a/Supersign/GrandSlam/Model/GrandSlamLoginData.swift b/Supersign/Sources/Supersign/GrandSlam/Model/GrandSlamLoginData.swift
similarity index 100%
rename from Supersign/GrandSlam/Model/GrandSlamLoginData.swift
rename to Supersign/Sources/Supersign/GrandSlam/Model/GrandSlamLoginData.swift
diff --git a/Supersign/GrandSlam/Operations/GrandSlamAuthenticateOperation.swift b/Supersign/Sources/Supersign/GrandSlam/Operations/GrandSlamAuthenticateOperation.swift
similarity index 100%
rename from Supersign/GrandSlam/Operations/GrandSlamAuthenticateOperation.swift
rename to Supersign/Sources/Supersign/GrandSlam/Operations/GrandSlamAuthenticateOperation.swift
diff --git a/Supersign/GrandSlam/Operations/GrandSlamFetchAppTokensOperation.swift b/Supersign/Sources/Supersign/GrandSlam/Operations/GrandSlamFetchAppTokensOperation.swift
similarity index 100%
rename from Supersign/GrandSlam/Operations/GrandSlamFetchAppTokensOperation.swift
rename to Supersign/Sources/Supersign/GrandSlam/Operations/GrandSlamFetchAppTokensOperation.swift
diff --git a/Supersign/GrandSlam/Operations/GrandSlamTwoFactorAuthenticateOperation.swift b/Supersign/Sources/Supersign/GrandSlam/Operations/GrandSlamTwoFactorAuthenticateOperation.swift
similarity index 98%
rename from Supersign/GrandSlam/Operations/GrandSlamTwoFactorAuthenticateOperation.swift
rename to Supersign/Sources/Supersign/GrandSlam/Operations/GrandSlamTwoFactorAuthenticateOperation.swift
index bd4fb17..e0735a0 100644
--- a/Supersign/GrandSlam/Operations/GrandSlamTwoFactorAuthenticateOperation.swift
+++ b/Supersign/Sources/Supersign/GrandSlam/Operations/GrandSlamTwoFactorAuthenticateOperation.swift
@@ -8,7 +8,7 @@
import Foundation
-public protocol TwoFactorAuthDelegate: class {
+public protocol TwoFactorAuthDelegate: AnyObject {
func fetchCode(completion: @escaping (String?) -> Void)
}
diff --git a/Supersign/GrandSlam/Requests/Concrete/GrandSlamAppTokensRequest.swift b/Supersign/Sources/Supersign/GrandSlam/Requests/Concrete/GrandSlamAppTokensRequest.swift
similarity index 100%
rename from Supersign/GrandSlam/Requests/Concrete/GrandSlamAppTokensRequest.swift
rename to Supersign/Sources/Supersign/GrandSlam/Requests/Concrete/GrandSlamAppTokensRequest.swift
diff --git a/Supersign/GrandSlam/Requests/Concrete/GrandSlamAuthCompleteRequest.swift b/Supersign/Sources/Supersign/GrandSlam/Requests/Concrete/GrandSlamAuthCompleteRequest.swift
similarity index 100%
rename from Supersign/GrandSlam/Requests/Concrete/GrandSlamAuthCompleteRequest.swift
rename to Supersign/Sources/Supersign/GrandSlam/Requests/Concrete/GrandSlamAuthCompleteRequest.swift
diff --git a/Supersign/GrandSlam/Requests/Concrete/GrandSlamAuthInitRequest.swift b/Supersign/Sources/Supersign/GrandSlam/Requests/Concrete/GrandSlamAuthInitRequest.swift
similarity index 100%
rename from Supersign/GrandSlam/Requests/Concrete/GrandSlamAuthInitRequest.swift
rename to Supersign/Sources/Supersign/GrandSlam/Requests/Concrete/GrandSlamAuthInitRequest.swift
diff --git a/Supersign/GrandSlam/Requests/Concrete/GrandSlamTrustedDeviceRequest.swift b/Supersign/Sources/Supersign/GrandSlam/Requests/Concrete/GrandSlamTrustedDeviceRequest.swift
similarity index 100%
rename from Supersign/GrandSlam/Requests/Concrete/GrandSlamTrustedDeviceRequest.swift
rename to Supersign/Sources/Supersign/GrandSlam/Requests/Concrete/GrandSlamTrustedDeviceRequest.swift
diff --git a/Supersign/GrandSlam/Requests/Concrete/GrandSlamValidateRequest.swift b/Supersign/Sources/Supersign/GrandSlam/Requests/Concrete/GrandSlamValidateRequest.swift
similarity index 100%
rename from Supersign/GrandSlam/Requests/Concrete/GrandSlamValidateRequest.swift
rename to Supersign/Sources/Supersign/GrandSlam/Requests/Concrete/GrandSlamValidateRequest.swift
diff --git a/Supersign/GrandSlam/Requests/GrandSlamOperationRequest.swift b/Supersign/Sources/Supersign/GrandSlam/Requests/GrandSlamOperationRequest.swift
similarity index 91%
rename from Supersign/GrandSlam/Requests/GrandSlamOperationRequest.swift
rename to Supersign/Sources/Supersign/GrandSlam/Requests/GrandSlamOperationRequest.swift
index d30b7e7..1e840ab 100644
--- a/Supersign/GrandSlam/Requests/GrandSlamOperationRequest.swift
+++ b/Supersign/Sources/Supersign/GrandSlam/Requests/GrandSlamOperationRequest.swift
@@ -69,9 +69,9 @@ extension GrandSlamOperationRequest {
static var endpoint: GrandSlamEndpoint { \.gsService }
- func configure(request: inout URLRequest, deviceInfo: DeviceInfo, anisetteData: AnisetteData) {
- request.setValue("*/*", forHTTPHeaderField: "Accept")
- request.setValue(deviceInfo.clientInfo.userAgent, forHTTPHeaderField: "User-Agent")
+ func configure(request: inout HTTPRequest, deviceInfo: DeviceInfo, anisetteData: AnisetteData) {
+ request.headers["Accept"] = "*/*"
+ request.headers["User-Agent"] = deviceInfo.clientInfo.userAgent
}
func method(deviceInfo: DeviceInfo, anisetteData: AnisetteData) -> GrandSlamMethod {
diff --git a/Supersign/GrandSlam/Requests/GrandSlamRequest.swift b/Supersign/Sources/Supersign/GrandSlam/Requests/GrandSlamRequest.swift
similarity index 74%
rename from Supersign/GrandSlam/Requests/GrandSlamRequest.swift
rename to Supersign/Sources/Supersign/GrandSlam/Requests/GrandSlamRequest.swift
index 2be83ac..fa6055d 100644
--- a/Supersign/GrandSlam/Requests/GrandSlamRequest.swift
+++ b/Supersign/Sources/Supersign/GrandSlam/Requests/GrandSlamRequest.swift
@@ -30,10 +30,6 @@ protocol GrandSlamRequest {
static var endpoint: GrandSlamEndpoint { get }
- func configure(request: inout URLRequest, deviceInfo: DeviceInfo, anisetteData: AnisetteData)
+ func configure(request: inout HTTPRequest, deviceInfo: DeviceInfo, anisetteData: AnisetteData)
func method(deviceInfo: DeviceInfo, anisetteData: AnisetteData) -> GrandSlamMethod
}
-
-extension GrandSlamRequest {
-// func configure(request: inout URLRequest, deviceInfo: DeviceInfo, anisetteData: AnisetteData) {}
-}
diff --git a/Supersign/Sources/Supersign/GrandSlam/Requests/GrandSlamTwoFactorRequest.swift b/Supersign/Sources/Supersign/GrandSlam/Requests/GrandSlamTwoFactorRequest.swift
new file mode 100644
index 0000000..e9665d2
--- /dev/null
+++ b/Supersign/Sources/Supersign/GrandSlam/Requests/GrandSlamTwoFactorRequest.swift
@@ -0,0 +1,33 @@
+//
+// GrandSlamTwoFactorRequest.swift
+// Supersign
+//
+// Created by Kabir Oberai on 20/11/19.
+// Copyright © 2019 Kabir Oberai. All rights reserved.
+//
+
+import Foundation
+
+protocol GrandSlamTwoFactorRequest: GrandSlamRequest {
+ var loginData: GrandSlamLoginData { get }
+ var extraHeaders: [String: String] { get }
+}
+
+extension GrandSlamTwoFactorRequest {
+
+ var extraHeaders: [String: String] { [:] }
+
+ func configure(request: inout HTTPRequest, deviceInfo: DeviceInfo, anisetteData: AnisetteData) {
+ request.headers["Accept"] = "text/x-xml-plist"
+ request.headers["X-Apple-App-Info"] = "com.apple.gs.xcode.auth"
+ request.headers[DeviceInfo.xcodeVersionKey] = DeviceInfo.xcodeVersion
+ request.headers["X-Apple-Identity-Token"] = loginData.identityToken
+ anisetteData.dictionary.forEach { request.headers[$0] = $1 }
+ extraHeaders.forEach { request.headers[$0] = $1 }
+ }
+
+ func method(deviceInfo: DeviceInfo, anisetteData: AnisetteData) -> GrandSlamMethod {
+ .get
+ }
+
+}
diff --git a/Supersign/Sources/Supersign/HTTPClientProtocol/AsyncHTTPClient+HTTP.swift b/Supersign/Sources/Supersign/HTTPClientProtocol/AsyncHTTPClient+HTTP.swift
new file mode 100644
index 0000000..0baa914
--- /dev/null
+++ b/Supersign/Sources/Supersign/HTTPClientProtocol/AsyncHTTPClient+HTTP.swift
@@ -0,0 +1,142 @@
+//
+// AsyncHTTPClient+HTTP.swift
+//
+//
+// Created by Kabir Oberai on 05/05/21.
+//
+
+#if os(Linux)
+import Foundation
+import AsyncHTTPClient
+import NIO
+import NIOHTTP1
+import NIOSSL
+
+extension HTTPClient: HTTPClientProtocol {
+// private struct ReadError: Error {}
+//
+// private func read(
+// inputStream stream: InputStream,
+// chunkSize: Int,
+// eventLoop: EventLoop,
+// writer: @escaping (ByteBuffer) -> EventLoopFuture<Void>
+// ) -> EventLoopFuture<Void> {
+// var buf = ByteBuffer()
+// func _read() -> EventLoopFuture<Void> {
+// eventLoop.submit { () throws -> Int in
+// buf.clear()
+// return try buf.writeWithUnsafeMutableBytes(minimumWritableBytes: chunkSize) { raw in
+// let bound = raw.bindMemory(to: UInt8.self)
+// let res = stream.read(bound.baseAddress!, maxLength: bound.count)
+// guard res != -1 else { throw ReadError() }
+// return res
+// }
+// }.flatMap { bytesRead in
+// bytesRead == 0 ?
+// // we've reached the EOF
+// writer(buf) :
+// // there's more. Write and then keep reading.
+// writer(buf).flatMap(_read)
+// }
+// }
+// return _read()
+// }
+
+ @discardableResult
+ public func makeRequest(
+ _ request: HTTPRequest,
+ completion: @escaping (Result<HTTPResponse, Error>) -> Void
+ ) -> HTTPTask {
+// print("Requesting \(request.url)")
+
+ let headers = HTTPHeaders(request.headers.map { $0 })
+ let body: HTTPClient.Body?
+ switch request.body {
+ case .buffer(let data):
+ body = .data(data)
+// case .stream(let stream):
+// body = .stream { writer in
+// let eventLoop = writer.write(.byteBuffer(.init())).eventLoop
+// return self.read(inputStream: stream, chunkSize: 1024, eventLoop: eventLoop) {
+// writer.write(.byteBuffer($0))
+// }
+// }
+ case nil:
+ body = nil
+ }
+ let httpReq: HTTPClient.Request
+ do {
+ httpReq = try HTTPClient.Request(
+ url: request.url,
+ method: request.method.map(HTTPMethod.init(rawValue:)) ?? .GET,
+ headers: headers,
+ body: body
+ )
+ } catch {
+ completion(.failure(error))
+ return HTTPTask { }
+ }
+ let task = execute(request: httpReq, delegate: ResponseAccumulator(request: httpReq))
+ task.futureResult.map { result in
+ HTTPResponse(
+ url: request.url,
+ status: Int(result.status.code),
+ headers: [String: String](uniqueKeysWithValues: result.headers.map { $0 }),
+ body: result.body.flatMap { $0.getData(at: 0, length: $0.writerIndex) }
+ )
+ }.whenComplete(completion)
+ return HTTPTask { task.cancel() }
+ }
+}
+
+public final class AsyncHTTPClientFactory: HTTPClientFactory {
+ private static let appleRootPEM = """
+ -----BEGIN CERTIFICATE-----
+ MIIEuzCCA6OgAwIBAgIBAjANBgkqhkiG9w0BAQUFADBiMQswCQYDVQQGEwJVUzET
+ MBEGA1UEChMKQXBwbGUgSW5jLjEmMCQGA1UECxMdQXBwbGUgQ2VydGlmaWNhdGlv
+ biBBdXRob3JpdHkxFjAUBgNVBAMTDUFwcGxlIFJvb3QgQ0EwHhcNMDYwNDI1MjE0
+ MDM2WhcNMzUwMjA5MjE0MDM2WjBiMQswCQYDVQQGEwJVUzETMBEGA1UEChMKQXBw
+ bGUgSW5jLjEmMCQGA1UECxMdQXBwbGUgQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkx
+ FjAUBgNVBAMTDUFwcGxlIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAw
+ ggEKAoIBAQDkkakJH5HbHkdQ6wXtXnmELes2oldMVeyLGYne+Uts9QerIjAC6Bg+
+ +FAJ039BqJj50cpmnCRrEdCju+QbKsMflZ56DKRHi1vUFjczy8QPTc4UadHJGXL1
+ XQ7Vf1+b8iUDulWPTV0N8WQ1IxVLFVkds5T39pyez1C6wVhQZ48ItCD3y6wsIG9w
+ tj8BMIy3Q88PnT3zK0koGsj+zrW5DtleHNbLPbU6rfQPDgCSC7EhFi501TwN22IW
+ q6NxkkdTVcGvL0Gz+PvjcM3mo0xFfh9Ma1CWQYnEdGILEINBhzOKgbEwWOxaBDKM
+ aLOPHd5lc/9nXmW8Sdh2nzMUZaF3lMktAgMBAAGjggF6MIIBdjAOBgNVHQ8BAf8E
+ BAMCAQYwDwYDVR0TAQH/BAUwAwEB/zAdBgNVHQ4EFgQUK9BpR5R2Cf70a40uQKb3
+ R01/CF4wHwYDVR0jBBgwFoAUK9BpR5R2Cf70a40uQKb3R01/CF4wggERBgNVHSAE
+ ggEIMIIBBDCCAQAGCSqGSIb3Y2QFATCB8jAqBggrBgEFBQcCARYeaHR0cHM6Ly93
+ d3cuYXBwbGUuY29tL2FwcGxlY2EvMIHDBggrBgEFBQcCAjCBthqBs1JlbGlhbmNl
+ IG9uIHRoaXMgY2VydGlmaWNhdGUgYnkgYW55IHBhcnR5IGFzc3VtZXMgYWNjZXB0
+ YW5jZSBvZiB0aGUgdGhlbiBhcHBsaWNhYmxlIHN0YW5kYXJkIHRlcm1zIGFuZCBj
+ b25kaXRpb25zIG9mIHVzZSwgY2VydGlmaWNhdGUgcG9saWN5IGFuZCBjZXJ0aWZp
+ Y2F0aW9uIHByYWN0aWNlIHN0YXRlbWVudHMuMA0GCSqGSIb3DQEBBQUAA4IBAQBc
+ NplMLXi37Yyb3PN3m/J20ncwT8EfhYOFG5k9RzfyqZtAjizUsZAS2L70c5vu0mQP
+ y3lPNNiiPvl4/2vIB+x9OYOLUyDTOMSxv5pPCmv/K/xZpwUJfBdAVhEedNO3iyM7
+ R6PVbyTi69G3cN8PReEnyvFteO3ntRcXqNx+IjXKJdXZD9Zr1KIkIxH3oayPc4Fg
+ xhtbCS+SsvhESPBgOJ4V9T0mZyCKM2r3DYLP3uujL/lTaltkwGMzd/c6ByxW69oP
+ IQ7aunMZT7XZNn/Bh1XZp5m5MkL72NVxnn6hUrcbvZNCJBIqxw8dtk2cXmPIS4AX
+ UKqK1drk/NAJBzewdXUh
+ -----END CERTIFICATE-----
+ """
+
+ private let client: HTTPClient
+ private init() {
+ // if ssl cert parsing fails we're screwed so we might as well force try
+ let appleRootCA = try! NIOSSLCertificate(bytes: Array(Self.appleRootPEM.utf8), format: .pem)
+ let config = HTTPClient.Configuration(
+ tlsConfiguration: .forClient(additionalTrustRoots: [.certificates([appleRootCA])]),
+ decompression: .enabled(limit: .none)
+ )
+ client = HTTPClient(eventLoopGroupProvider: .createNew, configuration: config)
+ }
+ public static let shared = AsyncHTTPClientFactory()
+
+ public func shutdown() {
+ try! client.syncShutdown()
+ }
+
+ public func makeClient() -> HTTPClientProtocol { client }
+}
+#endif
diff --git a/Supersign/Sources/Supersign/HTTPClientProtocol/HTTPClientProtocol.swift b/Supersign/Sources/Supersign/HTTPClientProtocol/HTTPClientProtocol.swift
new file mode 100644
index 0000000..659431e
--- /dev/null
+++ b/Supersign/Sources/Supersign/HTTPClientProtocol/HTTPClientProtocol.swift
@@ -0,0 +1,80 @@
+//
+// HTTPClientProtocol.swift
+//
+//
+// Created by Kabir Oberai on 05/05/21.
+//
+
+import Foundation
+
+public struct HTTPRequest {
+ public enum Body {
+ case buffer(Data)
+// case stream(InputStream)
+ }
+
+ public var url: URL
+ public var method: String?
+ public var headers: [String: String]
+ public var body: Body?
+
+ public init(
+ url: URL,
+ method: String? = nil,
+ headers: [String: String] = [:],
+ body: Body? = nil
+ ) {
+ self.url = url
+ self.method = method
+ self.headers = headers
+ self.body = body
+ }
+}
+
+public struct HTTPResponse {
+ public var url: URL
+ public var status: Int
+ public var headers: [String: String]
+ public var body: Data?
+
+ public init(
+ url: URL,
+ status: Int,
+ headers: [String: String] = [:],
+ body: Data? = nil
+ ) {
+ self.url = url
+ self.status = status
+ self.headers = headers
+ self.body = body
+ }
+}
+
+public final class HTTPTask {
+ private var cancellationHandler: () -> Void
+ public init(cancellationHandler: @escaping () -> Void) {
+ self.cancellationHandler = cancellationHandler
+ }
+ public func cancel() {
+ cancellationHandler()
+ }
+}
+
+public protocol HTTPClientProtocol {
+ @discardableResult
+ func makeRequest(_ request: HTTPRequest, completion: @escaping (Result<HTTPResponse, Error>) -> Void) -> HTTPTask
+}
+
+public protocol HTTPClientFactory {
+ static var shared: Self { get }
+ func shutdown() // client is invalidated after this
+ func makeClient() -> HTTPClientProtocol
+}
+
+public let defaultHTTPClientFactory: HTTPClientFactory.Type = {
+ #if os(Linux)
+ return AsyncHTTPClientFactory.self
+ #else
+ return URLHTTPClientFactory.self
+ #endif
+}()
diff --git a/Supersign/Sources/Supersign/HTTPClientProtocol/URLSession+HTTP.swift b/Supersign/Sources/Supersign/HTTPClientProtocol/URLSession+HTTP.swift
new file mode 100644
index 0000000..9dd26cf
--- /dev/null
+++ b/Supersign/Sources/Supersign/HTTPClientProtocol/URLSession+HTTP.swift
@@ -0,0 +1,72 @@
+//
+// URLSession+HTTPClientProtocol.swift
+//
+//
+// Created by Kabir Oberai on 05/05/21.
+//
+
+#if !os(Linux)
+import Foundation
+
+public struct UnknownHTTPError: Error {}
+
+extension URLSession: HTTPClientProtocol {
+ @discardableResult
+ public func makeRequest(
+ _ request: HTTPRequest,
+ completion: @escaping (Result<HTTPResponse, Error>) -> Void
+ ) -> HTTPTask {
+ var req = URLRequest(url: request.url)
+ req.httpMethod = request.method
+ request.headers.forEach { k, v in
+ req.setValue(v, forHTTPHeaderField: k)
+ }
+ switch request.body {
+ case .buffer(let data):
+ req.httpBody = data
+// case .stream(let stream):
+// req.httpBodyStream = stream
+ case nil:
+ break
+ }
+ let task = dataTask(with: req) { data, resp, error in
+ if let error = error {
+ return completion(.failure(error))
+ }
+ guard let httpResp = resp as? HTTPURLResponse else {
+ return completion(.failure(UnknownHTTPError()))
+ }
+ let headers = [String: String](
+ uniqueKeysWithValues: httpResp.allHeaderFields.compactMap { k, v in
+ guard let kStr = k as? String,
+ let vStr = v as? String
+ else { return nil }
+ return (kStr, vStr)
+ }
+ )
+ let resp = HTTPResponse(
+ url: request.url,
+ status: httpResp.statusCode,
+ headers: headers,
+ body: data
+ )
+ completion(.success(resp))
+ }
+ task.resume()
+ return HTTPTask { task.cancel() }
+ }
+}
+
+public final class URLHTTPClientFactory: HTTPClientFactory {
+ public static let shared = URLHTTPClientFactory()
+
+ // no need for cert handling since the Apple Root CA is already
+ // installed on any devices which support the Security APIs which
+ // would have been required to add the custom root anyway
+ private let session = URLSession(configuration: .ephemeral)
+ private init() {}
+
+ public func shutdown() {}
+ public func makeClient() -> HTTPClientProtocol { session }
+}
+#endif
diff --git a/Supersign/Installation/AppInstaller.swift b/Supersign/Sources/Supersign/Installation/AppInstaller.swift
similarity index 85%
rename from Supersign/Installation/AppInstaller.swift
rename to Supersign/Sources/Supersign/Installation/AppInstaller.swift
index c11726a..41bb00a 100644
--- a/Supersign/Installation/AppInstaller.swift
+++ b/Supersign/Sources/Supersign/Installation/AppInstaller.swift
@@ -47,15 +47,17 @@ public final class AppInstaller {
comment: ""
)
case .uploading:
+ // installing is a better name although this is
+ // technically uploading
return NSLocalizedString(
- "app_installer.stage.uploading",
- value: "Uploading",
+ "app_installer.stage.installing",
+ value: "Installing",
comment: ""
)
case .installing:
return NSLocalizedString(
- "app_installer.stage.installing",
- value: "Installing",
+ "app_installer.stage.verifying",
+ value: "Verifying",
comment: ""
)
}
@@ -101,12 +103,17 @@ public final class AppInstaller {
// synchronous
private func installSync(
+ connectionPreferences: Connection.Preferences,
progress: @escaping (Stage) -> Void
) throws {
defer { needsCancellation = false }
try cancelPoint()
- let connection = try Connection.connection(forUDID: udid, pairingKeys: pairingKeys) {
+ let connection = try Connection.connection(
+ forUDID: udid,
+ pairingKeys: pairingKeys,
+ preferences: connectionPreferences
+ ) {
progress(.connecting($0 * 4/6))
}
@@ -139,12 +146,16 @@ public final class AppInstaller {
}
public func install(
+ connectionPreferences: Connection.Preferences = .init(),
progress: @escaping (Stage) -> Void,
completion: @escaping (Result<(), Swift.Error>) -> Void
) {
installQueue.async {
completion(Result {
- try self.installSync(progress: progress)
+ try self.installSync(
+ connectionPreferences: connectionPreferences,
+ progress: progress
+ )
})
}
}
diff --git a/Supersign/Installation/Connection.swift b/Supersign/Sources/Supersign/Installation/Connection.swift
similarity index 77%
rename from Supersign/Installation/Connection.swift
rename to Supersign/Sources/Supersign/Installation/Connection.swift
index d7cba92..d0feebe 100644
--- a/Supersign/Installation/Connection.swift
+++ b/Supersign/Sources/Supersign/Installation/Connection.swift
@@ -10,7 +10,8 @@ import Foundation
import SwiftyMobileDevice
#if os(iOS)
-import libusbmuxd_ios
+import USBMuxSim
+import PortForwarding
public typealias PairingKeys = Data
@@ -22,7 +23,7 @@ private extension USBMuxSimulator {
}
func performAtomically<T>(_ operation: (USBMuxSimulator) throws -> T) throws -> T {
- var value: Result<T, Error>!
+ var value: Result<T, Swift.Error>!
__performAtomically { sim in
value = Result { try operation(sim) }
}
@@ -43,6 +44,17 @@ private class WeakBox<T: AnyObject> {
// there is at most one device per udid at any moment too.
public class Connection {
+ public enum Error: Swift.Error {
+ case portForwardingFailed
+ }
+
+ public struct Preferences {
+ public let usePortForwarding: Bool
+ public init(usePortForwarding: Bool = false) {
+ self.usePortForwarding = usePortForwarding
+ }
+ }
+
private static let label = "supersign"
private static var connections: [String: WeakBox<Connection>] = [:]
@@ -55,16 +67,26 @@ public class Connection {
private let udid: String
public let device: Device
public let client: LockdownClient
+ public var preferences: Preferences
- private init(udid: String, pairingKeys: PairingKeys, progress: (Double) -> Void) throws {
+ private init(
+ udid: String,
+ pairingKeys: PairingKeys,
+ preferences: Preferences,
+ progress: (Double) -> Void
+ ) throws {
progress(0/4)
+ self.preferences = preferences
self.udid = udid
#if os(iOS)
let simulatedDevice: USBMuxSimulatedDevice
- var ip = in_addr()
- if usbmux_forwarded_ip(&ip) == 0 {
+ if preferences.usePortForwarding {
+ var ip = in_addr()
+ guard usbmux_forwarded_ip(&ip) == 0 else {
+ throw Error.portForwardingFailed
+ }
NSLog("[SuperUSB] %@", "Using port forwarded device with ip \(String(cString: inet_ntoa(ip)!))")
simulatedDevice = PortForwardedDevice(ip: ip, pairingKeys: pairingKeys, udid: udid)
} else {
@@ -90,6 +112,7 @@ public class Connection {
public static func connection(
forUDID udid: String,
pairingKeys: PairingKeys,
+ preferences: Preferences = .init(),
progress: (Double) -> Void
) throws -> Connection {
try connectionsQueue.sync {
@@ -98,7 +121,12 @@ public class Connection {
progress(1)
return conn
}
- let conn = try Connection(udid: udid, pairingKeys: pairingKeys, progress: progress)
+ let conn = try Connection(
+ udid: udid,
+ pairingKeys: pairingKeys,
+ preferences: preferences,
+ progress: progress
+ )
connections[udid] = WeakBox(conn)
return conn
}
diff --git a/Supercharge Installer/ConnectionManager.swift b/Supersign/Sources/Supersign/Installation/ConnectionManager.swift
similarity index 83%
rename from Supercharge Installer/ConnectionManager.swift
rename to Supersign/Sources/Supersign/Installation/ConnectionManager.swift
index d23225c..2eb0d9f 100644
--- a/Supercharge Installer/ConnectionManager.swift
+++ b/Supersign/Sources/Supersign/Installation/ConnectionManager.swift
@@ -9,11 +9,11 @@
import Foundation
import SwiftyMobileDevice
-protocol ConnectionManagerDelegate: class {
+public protocol ConnectionManagerDelegate: AnyObject {
func connectionManager(_ manager: ConnectionManager, clientsDidChangeFrom oldValue: [ConnectionManager.Client])
}
-class ConnectionManager {
+public class ConnectionManager {
fileprivate struct ConnectionKey: Hashable, Equatable {
let udid: String
@@ -25,16 +25,16 @@ class ConnectionManager {
let deviceName: String
}
- struct Client {
- let udid: String
- let deviceName: String
+ public struct Client {
+ public let udid: String
+ public let deviceName: String
fileprivate init(key: ConnectionKey, value: ConnectionValue) {
self.udid = key.udid
self.deviceName = value.deviceName
}
- func isEquivalent(to other: Client) -> Bool {
+ public func isEquivalent(to other: Client) -> Bool {
udid == other.udid
}
}
@@ -45,7 +45,7 @@ class ConnectionManager {
}
}
- private(set) var clients: [Client] = [] {
+ public private(set) var clients: [Client] = [] {
didSet {
delegate?.connectionManager(self, clientsDidChangeFrom: oldValue)
}
@@ -53,13 +53,14 @@ class ConnectionManager {
private var token: USBMux.SubscriptionToken?
- weak var delegate: ConnectionManagerDelegate?
+ public weak var delegate: ConnectionManagerDelegate?
private func clientsDidChange() {
clients = clientsDict.sorted { $0.0.udid < $1.0.udid }.map(Client.init)
}
- init() throws {
+ public init(delegate: ConnectionManagerDelegate? = nil) throws {
+ self.delegate = delegate
self.token = try USBMux.subscribe { [weak self] event in
guard let self = self else { return }
self.handleEvent(event)
diff --git a/Supersign/Installation/DDIMounter.swift b/Supersign/Sources/Supersign/Installation/DDIMounter.swift
similarity index 92%
rename from Supersign/Installation/DDIMounter.swift
rename to Supersign/Sources/Supersign/Installation/DDIMounter.swift
index 500391b..3ff6242 100644
--- a/Supersign/Installation/DDIMounter.swift
+++ b/Supersign/Sources/Supersign/Installation/DDIMounter.swift
@@ -1,3 +1,5 @@
+#if false
+
//
// DDIMounter.swift
// Supersign
@@ -8,6 +10,9 @@
import Foundation
import SwiftyMobileDevice
+#if os(Linux)
+import FoundationNetworking
+#endif
public final class DDIMounter {
@@ -62,8 +67,8 @@ public final class DDIMounter {
func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) {
data.withUnsafeBytes { bytes in
let buf = bytes.bindMemory(to: UInt8.self)
- pipedStream.write(buf.baseAddress!, maxLength: buf.count)
- fileStream.write(buf.baseAddress!, maxLength: buf.count)
+ _ = pipedStream.write(buf.baseAddress!, maxLength: buf.count)
+ _ = fileStream.write(buf.baseAddress!, maxLength: buf.count)
}
}
@@ -122,6 +127,11 @@ public final class DDIMounter {
}
public func mountIfNeeded(local: DDILoc, fetchRemote: () throws -> DDILoc) throws {
+ #warning("we can't use CFSocketStream on Linux at all")
+ #if os(Linux)
+ // maybe just tear all of this down and download first, then mount the ddi.
+ fatalError("DDIMounter does not yet work on Linux")
+ #else
let mounted = try client.lookup(imageType: "Developer", resultType: MountedImage.self)
if mounted.signature != nil { return }
@@ -180,6 +190,9 @@ public final class DDIMounter {
}
_ = delegate
+ #endif
}
}
+
+#endif
diff --git a/Supersign/Installation/Debugger.swift b/Supersign/Sources/Supersign/Installation/Debugger.swift
similarity index 100%
rename from Supersign/Installation/Debugger.swift
rename to Supersign/Sources/Supersign/Installation/Debugger.swift
diff --git a/Supersign/Installation/HeartbeatHandler.swift b/Supersign/Sources/Supersign/Installation/HeartbeatHandler.swift
similarity index 97%
rename from Supersign/Installation/HeartbeatHandler.swift
rename to Supersign/Sources/Supersign/Installation/HeartbeatHandler.swift
index 2ebddc1..9c7f653 100644
--- a/Supersign/Installation/HeartbeatHandler.swift
+++ b/Supersign/Sources/Supersign/Installation/HeartbeatHandler.swift
@@ -107,7 +107,9 @@ public final class HeartbeatHandler {
do {
try self.beat(client: heartbeatClient, iteration: iteration)
} catch {
- NSLog("%@", "Heartbeat failed: \(error)")
+ "Heartbeat failed: \(error)".withCString {
+ NSLog("%s", $0)
+ }
// dispatching async should prevent stack overflows.
// We return to break out of the current loop.
return self.heartbeatQueue.asyncAfter(deadline: .now() + Self.restartInterval) {
diff --git a/Supersign/Installation/IPAInstaller.swift b/Supersign/Sources/Supersign/Installation/IPAInstaller.swift
similarity index 100%
rename from Supersign/Installation/IPAInstaller.swift
rename to Supersign/Sources/Supersign/Installation/IPAInstaller.swift
diff --git a/Supersign/Installation/IPAUploader.swift b/Supersign/Sources/Supersign/Installation/IPAUploader.swift
similarity index 100%
rename from Supersign/Installation/IPAUploader.swift
rename to Supersign/Sources/Supersign/Installation/IPAUploader.swift
diff --git a/Supersign/Installation/ProfileManager.swift b/Supersign/Sources/Supersign/Installation/ProfileManager.swift
similarity index 100%
rename from Supersign/Installation/ProfileManager.swift
rename to Supersign/Sources/Supersign/Installation/ProfileManager.swift
diff --git a/Supercharge Installer/Installer.swift b/Supersign/Sources/Supersign/Integration/SuperchargeInstaller.swift
similarity index 91%
rename from Supercharge Installer/Installer.swift
rename to Supersign/Sources/Supersign/Integration/SuperchargeInstaller.swift
index 4d269bc..d2e9af1 100644
--- a/Supercharge Installer/Installer.swift
+++ b/Supersign/Sources/Supersign/Integration/SuperchargeInstaller.swift
@@ -7,17 +7,18 @@
//
import Foundation
-import Supersign
import SwiftyMobileDevice
extension LockdownClient {
- static let installerLabel = "supersign-installer"
+ static let installerLabel = "supersign"
}
-protocol InstallerDelegate: class {
+#if !os(iOS)
+
+public protocol SuperchargeInstallerDelegate: AnyObject {
func fetchCode(completion: @escaping (String?) -> Void)
func fetchTeam(fromTeams teams: [DeveloperServicesTeam], completion: @escaping (DeveloperServicesTeam?) -> Void)
- func presentMessage(_ message: Installer.Message)
+ func presentMessage(_ message: SuperchargeInstaller.Message)
func dismissMessage()
func installerDidUpdate(toStage stage: String, progress: Double?)
func installerDidComplete(withResult result: Result<(), Error>)
@@ -55,8 +56,8 @@ protocol InstallerDelegate: class {
)
}
-extension InstallerDelegate {
- func compressIfNeeded(
+extension SuperchargeInstallerDelegate {
+ public func compressIfNeeded(
payloadDir: URL,
progress: @escaping (Double?) -> Void,
completion: @escaping (URL?) -> Void
@@ -65,9 +66,9 @@ extension InstallerDelegate {
}
}
-final class Installer {
+public final class SuperchargeInstaller {
- enum Error: LocalizedError {
+ public enum Error: LocalizedError {
case alreadyInstalling
case deviceInfoFetchFailed
case noTeamFound
@@ -76,12 +77,12 @@ final class Installer {
case appCorrupted
case appPackagingFailed
- var errorDescription: String? {
+ public var errorDescription: String? {
"Installer.Error.\(self)"
}
}
- enum Message {
+ public enum Message {
case pairDevice
case unlockDevice
}
@@ -89,7 +90,7 @@ final class Installer {
let udid: String
let appleID: String
let password: String
- weak var delegate: InstallerDelegate?
+ public weak var delegate: SuperchargeInstallerDelegate?
private var appInstaller: AppInstaller?
@@ -127,7 +128,7 @@ final class Installer {
delegate = nil
}
- func cancel() {
+ public func cancel() {
completion(.failure(Error.userCancelled))
}
@@ -147,11 +148,11 @@ final class Installer {
return true
}
- init(
+ public init(
udid: String,
appleID: String,
password: String,
- delegate: InstallerDelegate
+ delegate: SuperchargeInstallerDelegate
) {
self.udid = udid
self.appleID = appleID
@@ -162,7 +163,7 @@ final class Installer {
private func performWithRecovery<T>(hasPrompted: Bool = false, block: () throws -> T) throws -> T {
guard shouldContinue() else { throw Error.userCancelled }
- func recurse(_ message: Installer.Message) throws -> T {
+ func recurse(_ message: SuperchargeInstaller.Message) throws -> T {
if !hasPrompted { delegate?.presentMessage(message) }
// allow some time before recursing (even if TCO, we should probably not overdo it)
Thread.sleep(forTimeInterval: 0.5)
@@ -190,7 +191,11 @@ final class Installer {
// we can't reuse any previously created client because we need to perform a handshake this time
let lockdownClient = try performWithRecovery {
- try LockdownClient(device: device, label: LockdownClient.installerLabel, performHandshake: true)
+ try LockdownClient(
+ device: device,
+ label: LockdownClient.installerLabel,
+ performHandshake: true
+ )
}
try lockdownClient.setValue(udid, forDomain: "com.apple.mobile.wireless_lockdown", key: "WirelessBuddyID")
@@ -237,7 +242,7 @@ final class Installer {
team: DeveloperServicesTeam,
appDir: URL
) {
- guard self.updateStage(to: "Packaging app"),
+ guard self.updateStage(to: "Packaging"),
self.updateProgress(to: nil)
else { return }
@@ -279,9 +284,15 @@ final class Installer {
return completion(.failure(error))
}
- let signingInfoManager = KeyValueSigningInfoManager(
+ #warning("Persist manager on Windows/Linux")
+ let signingInfoManager: SigningInfoManager
+ #if os(macOS)
+ signingInfoManager = KeyValueSigningInfoManager(
storage: KeychainStorage(service: "com.kabiroberai.Supercharge-Installer.credentials")
)
+ #else
+ signingInfoManager = MemoryBackedSigningInfoManager()
+ #endif
let context: SigningContext
do {
@@ -372,10 +383,9 @@ final class Installer {
}
}
- private func installOnQueue() {
+ private func installOnQueue(ipa: URL) {
guard self.updateStage(to: "Unpacking app") else { return }
- let ipa = Bundle.main.url(forResource: "Supercharge", withExtension: "ipa")!
if FileManager.default.fileExists(atPath: tempDir.path) {
try? FileManager.default.removeItem(at: tempDir)
}
@@ -401,16 +411,16 @@ final class Installer {
)
}
- func install() {
+ public func install(ipa: URL) {
installQueue.async {
- self.installOnQueue()
+ self.installOnQueue(ipa: ipa)
}
}
}
-extension Installer: TwoFactorAuthDelegate {
- func fetchCode(completion: @escaping (String?) -> Void) {
+extension SuperchargeInstaller: TwoFactorAuthDelegate {
+ public func fetchCode(completion: @escaping (String?) -> Void) {
delegate?.fetchCode { code in
self.installQueue.async {
completion(code)
@@ -418,3 +428,5 @@ extension Installer: TwoFactorAuthDelegate {
}
}
}
+
+#endif
diff --git a/Supersign/Sources/Supersign/Integration/Superconfig.swift b/Supersign/Sources/Supersign/Integration/Superconfig.swift
new file mode 100644
index 0000000..7724a0d
--- /dev/null
+++ b/Supersign/Sources/Supersign/Integration/Superconfig.swift
@@ -0,0 +1,45 @@
+//
+// Superconfig.swift
+//
+//
+// Created by Kabir Oberai on 02/05/21.
+//
+
+import Foundation
+
+public struct Superconfig: Codable {
+ // Stuff that needs to come from the installer
+ public let udid: String
+ public let pairingKeys: Data
+ public let deviceInfo: DeviceInfo
+
+ // Stuff that can also be fetched in-app
+ public let preferredTeamID: String
+ public let preferredSigningInfo: SigningInfo?
+ public let appleID: String
+ public let token: DeveloperServicesLoginToken
+
+ public init(
+ udid: String,
+ pairingKeys: Data,
+ deviceInfo: DeviceInfo,
+ preferredTeamID: String,
+ preferredSigningInfo: SigningInfo?,
+ appleID: String,
+ token: DeveloperServicesLoginToken
+ ) {
+ self.udid = udid
+ self.pairingKeys = pairingKeys
+ self.deviceInfo = deviceInfo
+ self.preferredTeamID = preferredTeamID
+ self.preferredSigningInfo = preferredSigningInfo
+ self.appleID = appleID
+ self.token = token
+ }
+
+ public static let filename = "Superconfig.plist"
+ public static let encoder = PropertyListEncoder()
+ public func save(inAppDir appDir: URL) throws {
+ try Self.encoder.encode(self).write(to: appDir.appendingPathComponent(Self.filename))
+ }
+}
diff --git a/Supersign/Model/Certificate/Certificate.swift b/Supersign/Sources/Supersign/Model/Certificate/Certificate.swift
similarity index 99%
rename from Supersign/Model/Certificate/Certificate.swift
rename to Supersign/Sources/Supersign/Model/Certificate/Certificate.swift
index f748f9e..c4234df 100644
--- a/Supersign/Model/Certificate/Certificate.swift
+++ b/Supersign/Sources/Supersign/Model/Certificate/Certificate.swift
@@ -7,6 +7,7 @@
//
import Foundation
+import CSupersign
/// A certificate in DER format
public final class Certificate: Codable {
diff --git a/Supersign/Model/Entitlements/Entitlement.swift b/Supersign/Sources/Supersign/Model/Entitlements/Entitlement.swift
similarity index 100%
rename from Supersign/Model/Entitlements/Entitlement.swift
rename to Supersign/Sources/Supersign/Model/Entitlements/Entitlement.swift
diff --git a/Supersign/Model/Entitlements/EntitlementTypes.swift b/Supersign/Sources/Supersign/Model/Entitlements/EntitlementTypes.swift
similarity index 98%
rename from Supersign/Model/Entitlements/EntitlementTypes.swift
rename to Supersign/Sources/Supersign/Model/Entitlements/EntitlementTypes.swift
index d1055bc..6a11566 100644
--- a/Supersign/Model/Entitlements/EntitlementTypes.swift
+++ b/Supersign/Sources/Supersign/Model/Entitlements/EntitlementTypes.swift
@@ -17,10 +17,10 @@ extension EntitlementContainer {
TeamIdentifierEntitlement.self,
KeychainAccessGroupsEntitlement.self,
GetTaskAllowEntitlement.self,
- AssociatedDomainsEntitlement.self,
+// AssociatedDomainsEntitlement.self,
APSEnvironmentEntitlement.self,
AppGroupEntitlement.self,
- NetworkExtensionEntitlement.self,
+// NetworkExtensionEntitlement.self,
MultipathEntitlement.self,
VPNConfigurationEntitlement.self,
SiriKitEntitlement.self,
diff --git a/Supersign/Model/Entitlements/Entitlements.swift b/Supersign/Sources/Supersign/Model/Entitlements/Entitlements.swift
similarity index 99%
rename from Supersign/Model/Entitlements/Entitlements.swift
rename to Supersign/Sources/Supersign/Model/Entitlements/Entitlements.swift
index 206d328..b654ef6 100644
--- a/Supersign/Model/Entitlements/Entitlements.swift
+++ b/Supersign/Sources/Supersign/Model/Entitlements/Entitlements.swift
@@ -8,6 +8,7 @@
import Foundation
import ProtoCodable
+import Superutils
public struct EntitlementContainer: ProtoCodableContainer {
public var value: Entitlement
diff --git a/Supersign/Model/Keypair/Keypair.swift b/Supersign/Sources/Supersign/Model/Keypair/Keypair.swift
similarity index 98%
rename from Supersign/Model/Keypair/Keypair.swift
rename to Supersign/Sources/Supersign/Model/Keypair/Keypair.swift
index 8caa0a7..e60921e 100644
--- a/Supersign/Model/Keypair/Keypair.swift
+++ b/Supersign/Sources/Supersign/Model/Keypair/Keypair.swift
@@ -7,6 +7,7 @@
//
import Foundation
+import CSupersign
public struct PrivateKey: Codable {
public let data: Data
diff --git a/Supersign/Model/Mobileprovision/Mobileprovision.swift b/Supersign/Sources/Supersign/Model/Mobileprovision/Mobileprovision.swift
similarity index 99%
rename from Supersign/Model/Mobileprovision/Mobileprovision.swift
rename to Supersign/Sources/Supersign/Model/Mobileprovision/Mobileprovision.swift
index 91ddb1d..85e82f9 100644
--- a/Supersign/Model/Mobileprovision/Mobileprovision.swift
+++ b/Supersign/Sources/Supersign/Model/Mobileprovision/Mobileprovision.swift
@@ -7,6 +7,7 @@
//
import Foundation
+import CSupersign
public final class Mobileprovision: Decodable {
diff --git a/Supersign/Signer/Signer.swift b/Supersign/Sources/Supersign/Signer/Signer.swift
similarity index 74%
rename from Supersign/Signer/Signer.swift
rename to Supersign/Sources/Supersign/Signer/Signer.swift
index 8ae8056..779a4bd 100644
--- a/Supersign/Signer/Signer.swift
+++ b/Supersign/Sources/Supersign/Signer/Signer.swift
@@ -20,17 +20,21 @@ public struct Signer {
case .noSigners:
return NSLocalizedString("signer.error.no_signers", value: "No signers found", comment: "")
case .errorReading(let file):
- return String.localizedStringWithFormat(
- NSLocalizedString(
- "signer.error.error_reading", value: "Error while reading %@", comment: ""
- ), "\(file)"
- )
+ return "\(file)".withCString {
+ String.localizedStringWithFormat(
+ NSLocalizedString(
+ "signer.error.error_reading", value: "Error while reading %s", comment: ""
+ ), $0
+ )
+ }
case .errorWriting(let file):
- return String.localizedStringWithFormat(
- NSLocalizedString(
- "signer.error.error_writing", value: "Error while writing %@", comment: ""
- ), "\(file)"
- )
+ return "\(file)".withCString {
+ String.localizedStringWithFormat(
+ NSLocalizedString(
+ "signer.error.error_writing", value: "Error while writing %s", comment: ""
+ ), $0
+ )
+ }
}
}
}
@@ -57,11 +61,12 @@ public struct Signer {
for (url, info) in provisioningDict {
let infoPlist = url.appendingPathComponent("Info.plist")
- guard let dict = NSMutableDictionary(contentsOf: infoPlist) else {
- return completion(.failure(Error.errorReading(infoPlist.lastPathComponent)))
- }
- dict[kCFBundleIdentifierKey as String] = info.newBundleID
- guard dict.write(to: infoPlist, atomically: true) else {
+ guard let data = try? Data(contentsOf: infoPlist),
+ let dict = try? PropertyListSerialization.propertyList(from: data, format: nil) as? [String: Any]
+ else { return completion(.failure(Error.errorReading(infoPlist.lastPathComponent))) }
+ let nsDict = NSMutableDictionary(dictionary: dict)
+ nsDict["CFBundleIdentifier"] = info.newBundleID
+ guard nsDict.write(to: infoPlist, atomically: true) else {
return completion(.failure(Error.errorWriting(infoPlist.lastPathComponent)))
}
diff --git a/Supersign/SignerImpl/SignerImpl.swift b/Supersign/Sources/Supersign/Signer/SignerImpl.swift
similarity index 78%
rename from Supersign/SignerImpl/SignerImpl.swift
rename to Supersign/Sources/Supersign/Signer/SignerImpl.swift
index ecb7f88..7594479 100644
--- a/Supersign/SignerImpl/SignerImpl.swift
+++ b/Supersign/Sources/Supersign/Signer/SignerImpl.swift
@@ -7,8 +7,8 @@
//
import Foundation
-
-extension signer_t: CLinkedListElement {}
+import CSupersign
+import SignerSupport
/// a wrapper around signer_t
public struct SignerImpl {
@@ -43,18 +43,23 @@ public struct SignerImpl {
}
}
- public let name: String
- private let sign: sign_func
- private let analyze: analyze_func
+ private let signer: UnsafePointer<signer_t>
+ public var name: String {
+ String(cString: signer.pointee.name)
+ }
- private init(signer: signer_t) {
- name = String(cString: signer.name)
- sign = signer.sign
- analyze = signer.analyze
+ private init(signer: UnsafePointer<signer_t>) {
+ self.signer = signer
}
public static func all() -> AnyCollection<SignerImpl> {
- return AnyCollection(CLinkedList(first: signer_list).lazy.map(SignerImpl.init))
+ var list = get_signers()
+ var arr: [SignerImpl] = []
+ while let curr = list {
+ arr.append(SignerImpl(signer: curr))
+ list = curr.pointee.next
+ }
+ return AnyCollection(arr)
}
public static func first() throws -> SignerImpl {
@@ -74,11 +79,23 @@ public struct SignerImpl {
try url.withUnsafeFileSystemRepresentation { bundlePath in
guard let bundlePath = bundlePath else { throw Error.badFilePath }
return try encoder.encode(ents).withUnsafeBytes { bytes in
+ let copy = UnsafeMutableBufferPointer<UInt8>.allocate(capacity: bytes.count)
+ bytes.copyBytes(to: copy)
// an XML plist should always be non-empty so force unwrapping baseAddress is safe
- entitlements_data_t(bundle_path: bundlePath, data: bytes.baseAddress!, len: bytes.count)
+ return entitlements_data_t(
+ bundle_path: strdup(bundlePath),
+ data: copy.baseAddress!,
+ len: copy.count
+ )
}
}
}
+ defer {
+ entsArray.forEach {
+ free(UnsafeMutablePointer(mutating: $0.bundle_path))
+ $0.data.deallocate()
+ }
+ }
try certificate.data().withUnsafeBytes { cert in
try privateKey.data.withUnsafeBytes { priv in
var exception: UnsafeMutablePointer<Int8>?
@@ -88,7 +105,7 @@ public struct SignerImpl {
let privBase = priv.baseAddress
else { throw Error.signer(nil) }
- guard sign(
+ guard signer.pointee.sign(
app.path,
certBase, cert.count,
privBase, priv.count,
@@ -131,7 +148,7 @@ public struct SignerImpl {
guard let path = path else { throw Error.badFilePath }
var exception: UnsafeMutablePointer<Int8>?
defer { exception.map { free($0) } }
- return try Data { analyze(path, &$0, &exception) }
+ return try Data { signer.pointee.analyze(path, &$0, &exception) }
.orThrow(Error.signer(exception.map { String(cString: $0) }))
}
}
diff --git a/Supersign/Signer/SigningContext.swift b/Supersign/Sources/Supersign/Signer/SigningContext.swift
similarity index 100%
rename from Supersign/Signer/SigningContext.swift
rename to Supersign/Sources/Supersign/Signer/SigningContext.swift
diff --git a/Supersign/Utilities/CHelpers.swift b/Supersign/Sources/Supersign/Utilities/CHelpers.swift
similarity index 100%
rename from Supersign/Utilities/CHelpers.swift
rename to Supersign/Sources/Supersign/Utilities/CHelpers.swift
diff --git a/Supersign/Utilities/KeyValueStorage.swift b/Supersign/Sources/Supersign/Utilities/KeyValueStorage.swift
similarity index 100%
rename from Supersign/Utilities/KeyValueStorage.swift
rename to Supersign/Sources/Supersign/Utilities/KeyValueStorage.swift
diff --git a/Supersign/Utilities/ProvisioningIdentifiers.swift b/Supersign/Sources/Supersign/Utilities/ProvisioningIdentifiers.swift
similarity index 100%
rename from Supersign/Utilities/ProvisioningIdentifiers.swift
rename to Supersign/Sources/Supersign/Utilities/ProvisioningIdentifiers.swift
diff --git a/Supersign/Utilities/RequestGrouper.swift b/Supersign/Sources/Supersign/Utilities/RequestGrouper.swift
similarity index 100%
rename from Supersign/Utilities/RequestGrouper.swift
rename to Supersign/Sources/Supersign/Utilities/RequestGrouper.swift
diff --git a/Supersign/Utilities/SigningInfo.swift b/Supersign/Sources/Supersign/Utilities/SigningInfo.swift
similarity index 100%
rename from Supersign/Utilities/SigningInfo.swift
rename to Supersign/Sources/Supersign/Utilities/SigningInfo.swift
diff --git a/Supersign/module.modulemap b/Supersign/Sources/Supersign/module.modulemap
similarity index 100%
rename from Supersign/module.modulemap
rename to Supersign/Sources/Supersign/module.modulemap
diff --git a/Supersign/Sources/SupersignCLI/main.swift b/Supersign/Sources/SupersignCLI/main.swift
new file mode 100644
index 0000000..5feda74
--- /dev/null
+++ b/Supersign/Sources/SupersignCLI/main.swift
@@ -0,0 +1,637 @@
+import Foundation
+import Supersign
+
+defer { defaultHTTPClientFactory.shared.shutdown() }
+
+// nil = EOF
+func prompt(_ message: String) -> String? {
+ if !message.isEmpty {
+ print(message, terminator: "")
+ }
+ return readLine()
+}
+
+func getPassword(_ message: String) -> String? {
+ if !message.isEmpty {
+ print(message, terminator: "")
+ }
+
+ var origAttr = termios()
+ tcgetattr(STDIN_FILENO, &origAttr)
+
+ var newAttr = origAttr
+ newAttr.c_lflag = newAttr.c_lflag & ~tcflag_t(ECHO)
+ tcsetattr(STDIN_FILENO, TCSANOW, &newAttr)
+
+ let password = prompt("")
+
+ tcsetattr(STDIN_FILENO, TCSANOW, &origAttr)
+ print()
+
+ return password
+}
+
+func chooseNumber(in range: Range<Int>) -> Int {
+ print("Choice (\(range.lowerBound)-\(range.upperBound - 1)): ", terminator: "")
+ guard let choice = readLine().flatMap(Int.init), range.contains(choice)
+ else { return chooseNumber(in: range) }
+ return choice
+}
+
+func choose<T>(
+ from elements: [T],
+ onNoElement: () throws -> T,
+ multiPrompt: @autoclosure () -> String,
+ formatter: (T) throws -> String
+) rethrows -> T {
+ switch elements.count {
+ case 0:
+ return try onNoElement()
+ case 1:
+ return elements[0]
+ default:
+ print(multiPrompt())
+ try elements.enumerated().forEach { index, element in
+ try print("\(index): \(formatter(element))")
+ }
+ let choice = chooseNumber(in: elements.indices)
+ return elements[choice]
+ }
+}
+
+class SupersignCLIDelegate: SuperchargeInstallerDelegate {
+ let completion: () -> Void
+ init(completion: @escaping () -> Void) {
+ self.completion = completion
+ }
+
+ func fetchCode(completion: @escaping (String?) -> Void) {
+ let code = prompt("Code: ")
+ completion(code)
+ }
+
+ func fetchTeam(fromTeams teams: [DeveloperServicesTeam], completion: @escaping (DeveloperServicesTeam?) -> Void) {
+ let selected = choose(
+ from: teams,
+ onNoElement: { fatalError() },
+ multiPrompt: "Select a team",
+ formatter: {
+ "\($0.name) (\($0.id))"
+ }
+ )
+ completion(selected)
+ }
+
+ func presentMessage(_ message: SuperchargeInstaller.Message) {
+ switch message {
+ case .pairDevice:
+ print("\nPlease tap 'trust' on your device...", terminator: "")
+ case .unlockDevice:
+ print("\nPlease unlock your device...", terminator: "")
+ }
+ fflush(stdout)
+ }
+
+ func dismissMessage() {
+ print("\nContinuing...", terminator: "")
+ fflush(stdout)
+ }
+
+ var prevStage: String?
+ var prevProgress: String?
+
+ func installerDidUpdate(toStage stage: String, progress: Double?) {
+ let progString: String?
+ if let progress = progress {
+ let progInt = Int(progress * 100)
+ if progInt < 10 {
+ progString = " \(progInt)%"
+ } else if progInt < 100 {
+ progString = " \(progInt)%"
+ } else {
+ progString = "\(progInt)%"
+ }
+ } else {
+ progString = nil
+ }
+
+ defer {
+ prevStage = stage
+ prevProgress = progString
+ }
+
+ if stage != prevStage {
+ if let progString = progString {
+ print("\n[\(stage)] \(progString)", terminator: "")
+ fflush(stdout)
+ } else {
+ print("\n===[\(stage)]===", terminator: "")
+ fflush(stdout)
+ }
+ } else if progString != prevProgress {
+ if let progString = progString {
+ print("\r[\(stage)] \(progString)", terminator: "")
+ fflush(stdout)
+ } else {
+ print("\r[\(stage)]", terminator: "")
+ fflush(stdout)
+ }
+ }
+ }
+
+ func installerDidComplete(withResult result: Result<(), Error>) {
+ print()
+ switch result {
+ case .success:
+ print("Complete!")
+ case .failure(let error):
+ print("Failed :(")
+ print("Error: \(error)")
+ }
+ completion()
+ }
+
+ func decompress(
+ ipa: URL,
+ in directory: URL,
+ progress: @escaping (Double?) -> Void,
+ completion: @escaping (_ success: Bool) -> Void
+ ) {
+ progress(nil)
+
+ let unzip = Process()
+ unzip.launchPath = "/usr/bin/unzip"
+ unzip.arguments = ["-q", ipa.path, "-d", directory.path]
+ unzip.launch()
+ unzip.waitUntilExit()
+ guard unzip.terminationStatus == 0 else { return completion(false) }
+
+ completion(true)
+ }
+
+ func compressIfNeeded(payloadDir: URL, progress: @escaping (Double?) -> Void, completion: @escaping (URL?) -> Void) {
+ progress(nil)
+
+ let dest = payloadDir.deletingLastPathComponent().appendingPathComponent("app.ipa")
+
+ let zip = Process()
+ zip.launchPath = "/usr/bin/zip"
+ zip.currentDirectoryPath = payloadDir.deletingLastPathComponent().path
+ zip.arguments = ["-yqru0", dest.path, "Payload"]
+ zip.launch()
+ zip.waitUntilExit()
+ guard zip.terminationStatus == 0 else { return completion(nil) }
+
+ completion(dest)
+ }
+}
+
+class ConnectionDelegate: ConnectionManagerDelegate {
+ var onConnect: (([ConnectionManager.Client]) -> Void)?
+ init(onConnect: @escaping ([ConnectionManager.Client]) -> Void) {
+ self.onConnect = onConnect
+ }
+
+ func connectionManager(_ manager: ConnectionManager, clientsDidChangeFrom oldValue: [ConnectionManager.Client]) {
+ onConnect?(manager.clients)
+ onConnect = nil
+ }
+}
+
+func main() throws {
+ let moduleBundle: Bundle
+ #if swift(>=5.5) || os(macOS)
+ moduleBundle = Bundle.module
+ #else
+ moduleBundle = Bundle(url: Bundle.main.url(forResource: "Supersign_SupersignCLI", withExtension: "resources")!)!
+ #endif
+ let app = moduleBundle.url(forResource: "Supercharge", withExtension: "ipa")!
+
+ guard let username = prompt("Apple ID: "),
+ let password = getPassword("Password: ")
+ else { return }
+
+ print("Waiting for device to be connected...")
+ var clients: [ConnectionManager.Client]!
+ let semaphore = DispatchSemaphore(value: 0)
+ let connDelegate = ConnectionDelegate { currClients in
+ clients = currClients
+ semaphore.signal()
+ }
+ try withExtendedLifetime(ConnectionManager(delegate: connDelegate)) {
+ semaphore.wait()
+ }
+
+ let client = choose(
+ from: clients,
+ onNoElement: { fatalError() },
+ multiPrompt: "Choose device",
+ formatter: { "\($0.deviceName) (\($0.udid))" }
+ )
+
+ print("Installing to device: \(client.deviceName) (\(client.udid))")
+
+ let installDelegate = SupersignCLIDelegate {
+ semaphore.signal()
+ }
+ let installer = SuperchargeInstaller(udid: client.udid, appleID: username, password: password, delegate: installDelegate)
+ installer.install(ipa: app)
+ semaphore.wait()
+ _ = installer
+}
+
+try main()
+
+//func main() throws {
+// let connManager = try ConnectionManager()
+// sleep(1)
+// print("Connected: \(connManager.clients)")
+//
+// let deviceInfo = DeviceInfo.current()!
+// let manager = DeveloperServicesLoginManager(deviceInfo: deviceInfo)
+//
+// guard let username = prompt("Username: "),
+// let password = getPassword("Password: ")
+// else { return }
+//
+// class TwoFactorFetcher: TwoFactorAuthDelegate {
+// func fetchCode(completion: @escaping (String?) -> Void) {
+// let code = prompt("Code: ")
+// completion(code)
+// }
+// }
+//
+// var tokenResult: Result<DeveloperServicesLoginToken, Error>!
+// let fetcher = TwoFactorFetcher()
+// let sem = DispatchSemaphore(value: 0)
+// manager.logIn(withUsername: username, password: password, twoFactorDelegate: fetcher) { result in
+// defer { sem.signal() }
+// tokenResult = result
+// }
+// sem.wait()
+// let token = try tokenResult.get()
+//
+// var teamsResult: Result<[DeveloperServicesTeam], Error>!
+// let client = DeveloperServicesClient(loginToken: token, deviceInfo: deviceInfo)
+// client.send(DeveloperServicesListTeamsRequest()) { result in
+// defer { sem.signal() }
+// teamsResult = result
+// }
+// sem.wait()
+// let teams = try teamsResult.get()
+//
+// let memManager = MemoryBackedSigningInfoManager()
+// let ctx = try SigningContext(
+// udid: "00008030-001409AA0298802E",
+// teamID: teams[0].id,
+// client: client,
+// signingInfoManager: memManager
+// )
+//
+// var signResult: Result<(), Error>!
+// let app = Bundle.module.url(forResource: "Supercharge", withExtension: "app")!
+// print("App: \(app)")
+//
+// let tmp = try FileManager.default.makeTemporaryDirectory()
+// defer { try? FileManager.default.removeItem(at: tmp) }
+//
+// let copied = tmp.appendingPathComponent("Supercharge.app")
+// try FileManager.default.copyItem(at: app, to: copied)
+//
+// Signer(context: ctx).sign(
+// app: copied,
+// status: { status in
+// print("[status] \(status)")
+// },
+// progress: { progress in
+// print("[progress] \(progress)")
+// },
+// completion: { result in
+// defer { sem.signal() }
+// signResult = result
+// }
+// )
+// sem.wait()
+// try signResult.get()
+//
+// print("Success!")
+//}
+//
+//try main()
+
+//if #available(macOS 10.12, *) {
+// RunLoop.main.perform(main)
+//}
+//RunLoop.main.run()
+
+//print("Connecting...")
+
+//let manager = try ConnectionManager()
+//Thread.sleep(forTimeInterval: 1)
+//print("Clients: \(manager.clients)")
+
+////
+//// main.swift
+//// SuperchargeInstallerCLI
+////
+//// Created by Kabir Oberai on 17/06/20.
+//// Copyright © 2020 Kabir Oberai. All rights reserved.
+////
+//
+//import Foundation
+//import Supersign
+//import SwiftyMobileDevice
+//
+//extension LockdownClient {
+// static let supersignLabel = "supercharge-installer"
+//}
+//
+//struct InstallerError: Error, CustomStringConvertible {
+// let description: String
+// init(_ description: String) {
+// self.description = description
+// }
+//}
+//
+//func printProgress(_ progress: Double, description: String) {
+// print("[\(String(format: "%.2f%%", progress * 100))] \(description)")
+//}
+//
+//func chooseNumber(in range: Range<Int>) -> Int {
+// print("Choice (\(range.lowerBound)-\(range.upperBound - 1)): ", terminator: "")
+// guard let choice = readLine().flatMap(Int.init), range.contains(choice)
+// else { return chooseNumber(in: range) }
+// return choice
+//}
+//
+//func choose<T>(
+// from elements: [T],
+// onNoElement: () throws -> T,
+// multiPrompt: @autoclosure () -> String,
+// formatter: (T) throws -> String
+//) rethrows -> T {
+// switch elements.count {
+// case 0:
+// return try onNoElement()
+// case 1:
+// return elements[0]
+// default:
+// print(multiPrompt())
+// try elements.enumerated().forEach { index, element in
+// try print("\(index): \(formatter(element))")
+// }
+// let choice = chooseNumber(in: elements.indices)
+// return elements[choice]
+// }
+//}
+//
+//func performWithRecovery<T>(shouldPrompt: Bool = true, block: () throws -> T) rethrows -> T {
+// func recurse(_ message: String) throws -> T {
+// if shouldPrompt { print(message) }
+// // allow some time before recursing (even if TCO)
+// Thread.sleep(forTimeInterval: 0.5)
+// return try performWithRecovery(shouldPrompt: false, block: block)
+// }
+//
+// do {
+// return try block()
+// } catch let error as LockdownClient.Error where error == .pairingDialogResponsePending {
+// return try recurse("Please pair your device...")
+// } catch let error as LockdownClient.Error where error == .passwordProtected {
+// return try recurse("Please unlock your device...")
+// } catch {
+// throw error
+// }
+//}
+//
+//struct IDeviceInfo {
+// let udid: String
+// let pairingKeys: Data
+//
+// static func retrieve() throws -> IDeviceInfo {
+// print("Looking for devices...")
+// var devices: [Device]
+// repeat {
+// // using a Set uniques devices that are available via network+usb
+// let udids = try Set(Device.udids()).sorted()
+// devices = udids.compactMap { try? Device(udid: $0) }
+// } while devices.isEmpty
+// print("Connected!")
+// let device = try choose(
+// from: devices,
+// onNoElement: {
+// throw InstallerError("No devices found. Please attach a device and try again.")
+// },
+// multiPrompt: "Select a device",
+// formatter: { device in
+// let client = try LockdownClient(device: device, label: LockdownClient.supersignLabel, performHandshake: false)
+// return try "\(client.deviceName()) (\(device.udid()))"
+// }
+// )
+//
+// // we can't reuse the previously created client because we need to perform a handshake this time
+// let client = try performWithRecovery {
+// try LockdownClient(device: device, label: LockdownClient.supersignLabel, performHandshake: true)
+// }
+// let udid = try device.udid()
+//
+// try client.setValue(udid, forDomain: "com.apple.mobile.wireless_lockdown", key: "WirelessBuddyID")
+// try client.setValue(true, forDomain: "com.apple.mobile.wireless_lockdown", key: "EnableWifiConnections")
+//
+// // now create a new pair record, temporarily removing the existing one. This is necessary
+// // because if two machines try accessing lockdown with the same device wirelessly, it'll
+// // fail during the heartbeat
+// let oldRecord = try USBMux.pairRecord(forUDID: udid)
+// try USBMux.deletePairRecord(forUDID: udid)
+//
+// let newRecord: Data
+// do {
+// defer { try? USBMux.savePairRecord(oldRecord, forUDID: udid) }
+// try performWithRecovery { try client.pair() }
+// newRecord = try USBMux.pairRecord(forUDID: udid)
+// }
+//
+// return IDeviceInfo(udid: udid, pairingKeys: newRecord)
+// }
+//}
+//
+//class LoginManager: TwoFactorAuthDelegate {
+//
+// let deviceInfo: DeviceInfo
+// init(deviceInfo: DeviceInfo) {
+// self.deviceInfo = deviceInfo
+// }
+//
+// private func prompt(_ message: String) -> String {
+// print(message, terminator: "")
+// return readLine() ?? prompt(message)
+// }
+//
+// func logIn() throws -> (String, DeveloperServicesLoginToken) {
+// let username = prompt("Apple ID: ")
+// let password = String(cString: getpass("Password: "))
+//
+// let group = DispatchGroup()
+// group.enter()
+// var result: Result<DeveloperServicesLoginToken, Error>?
+// DeveloperServicesLoginManager(deviceInfo: deviceInfo).logIn(
+// withUsername: username,
+// password: password,
+// twoFactorDelegate: self
+// ) { res in
+// result = res
+// group.leave()
+// }
+// group.wait()
+//
+// return (username, try result!.get())
+// }
+//
+// func fetchCode(completion: @escaping (String) -> Void) {
+// completion(prompt("2FA Code: "))
+// }
+//
+//}
+//
+//func fetchTeam(client: DeveloperServicesClient) throws -> DeveloperServicesTeam {
+// var result: Result<[DeveloperServicesTeam], Error>?
+// let group = DispatchGroup()
+// group.enter()
+// client.send(DeveloperServicesListTeamsRequest()) { res in
+// result = res
+// group.leave()
+// }
+// group.wait()
+// let teams = try result!.get()
+// return try choose(
+// from: teams,
+// onNoElement: {
+// throw InstallerError("Could not find any development teams associated with this Apple ID")
+// },
+// multiPrompt: "Select a team",
+// formatter: { "\($0.name) (\($0.id.rawValue))" }
+// )
+//}
+//
+//func makeAppDir() throws -> URL {
+// let template = URL(fileURLWithPath: "/Users/kabiroberai/Desktop/Supercharge-Template.app")
+//
+// let temp = FileManager.default.temporaryDirectory.appendingPathComponent("Supercharge-Staging")
+// if FileManager.default.fileExists(atPath: temp.path) {
+// try FileManager.default.removeItem(at: temp)
+// }
+// try FileManager.default.createDirectory(at: temp, withIntermediateDirectories: true, attributes: nil)
+//
+// let dest = temp.appendingPathComponent("Supercharge.app")
+// try FileManager.default.copyItem(at: template, to: dest)
+// return dest
+//}
+//
+////func package(app: URL) throws -> URL {
+//// let tempDir = app.deletingLastPathComponent()
+//// let payloadDir = tempDir.appendingPathComponent("Payload")
+//// if FileManager.default.fileExists(atPath: payloadDir.path) {
+//// try FileManager.default.removeItem(at: payloadDir)
+//// }
+//// try FileManager.default.createDirectory(at: payloadDir, withIntermediateDirectories: true, attributes: nil)
+//// try FileManager.default.moveItem(at: app, to: payloadDir.appendingPathComponent(app.lastPathComponent))
+////
+//// let zipProcess = Process()
+//// zipProcess.executableURL = URL(fileURLWithPath: "/usr/bin/zip")
+//// zipProcess.arguments = ["-r", "Supercharge.ipa", payloadDir.lastPathComponent]
+//// zipProcess.currentDirectoryURL = tempDir
+//// try zipProcess.run()
+//// zipProcess.waitUntilExit()
+//// guard zipProcess.terminationStatus == 0 else { throw InstallerError("Failed to package signed app") }
+////
+//// return tempDir.appendingPathComponent("Supercharge.ipa")
+////}
+//
+//func install(
+// app: URL,
+// iDeviceInfo: IDeviceInfo,
+// team: DeveloperServicesTeam,
+// client: DeveloperServicesClient
+//) throws {
+// let context = try SigningContext(
+// udid: iDeviceInfo.udid,
+// teamID: team.id,
+// client: client,
+// signingInfoManager: MemoryBackedSigningInfoManager(),
+// platform: .iOS
+// )
+//
+// let group = DispatchGroup()
+// var result: Result<(), Error>?
+// var currProgress: Double = 0
+// var currStatus: String?
+// group.enter()
+// Signer(context: context).sign(
+// app: app,
+// status: { status in
+// currStatus = status
+// printProgress(currProgress, description: status)
+// },
+// progress: { progress in
+// currProgress = progress
+// currStatus.map { printProgress(progress, description: $0) }
+// },
+// completion: { res in
+// result = res
+// group.leave()
+// }
+// )
+// group.wait()
+// try result!.get()
+//
+//// print("Packaging app...")
+//// let ipa = try package(app: app)
+//
+// group.enter()
+// AppInstaller(app: app, udid: iDeviceInfo.udid, pairingKeys: iDeviceInfo.pairingKeys).install(
+// progress: { stage in
+// printProgress(stage.displayProgress, description: stage.displayName)
+// }, completion: { res in
+// result = res
+// group.leave()
+// }
+// )
+//
+// group.wait()
+// try result!.get()
+//}
+//
+//func main() throws {
+// guard let deviceInfo: DeviceInfo = .current() else {
+// throw InstallerError("Failed to fetch hardware info")
+// }
+//
+// let iDeviceInfo: IDeviceInfo = try .retrieve()
+//
+// let (appleID, token) = try LoginManager(deviceInfo: deviceInfo).logIn()
+// print("Logged in! Fetching teams...")
+// let client = DeveloperServicesClient(loginToken: token, deviceInfo: deviceInfo)
+// let team = try fetchTeam(client: client)
+//
+// let appDir = try makeAppDir()
+// let tempDir = appDir.deletingLastPathComponent()
+// defer { try? FileManager.default.removeItem(at: tempDir) }
+//
+// let config = Superconfig(
+// udid: iDeviceInfo.udid,
+// pairingKeys: iDeviceInfo.pairingKeys,
+// deviceInfo: deviceInfo,
+// preferredTeamID: team.id.rawValue,
+// appleID: appleID,
+// token: token
+// )
+// try config.save(inAppDir: appDir)
+//
+// try install(app: appDir, iDeviceInfo: iDeviceInfo, team: team, client: client)
+//}
+//
+//do {
+// try main()
+//} catch {
+// print("Error: \(error)")
+//}