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.

Support API key based auth

Kabir Oberaiaf8d5f5c3cbf
diff --git a/Sources/Supersign/DeveloperServices/ASCKey.swift b/Sources/Supersign/DeveloperServices/ASCKey.swift
new file mode 100644
index 0000000..086f7c5
--- /dev/null
+++ b/Sources/Supersign/DeveloperServices/ASCKey.swift
@@ -0,0 +1,100 @@
+import Foundation
+import Crypto
+
+public struct ASCKey: Sendable {
+ public var id: String
+ public var issuerID: String
+ public var pem: String
+
+ public init(id: String, issuerID: String, pem: String) {
+ self.id = id
+ self.issuerID = issuerID
+ self.pem = pem
+ }
+}
+
+actor ASCJWTGenerator {
+ // the duration for which we generate JWTs.
+ // ASC allows a maximum of 20 minutes.
+ private static let ttl: TimeInterval = 60 * 20
+
+ // the minimum remaining ttl for us to consider reusing a previous key.
+ // that is, we reuse the last JWT if it has at least [threshold] seconds
+ // left before it expires.
+ private static let tolerance: TimeInterval = 60
+
+ private static let encoder: JSONEncoder = {
+ let encoder = JSONEncoder()
+ encoder.dateEncodingStrategy = .secondsSince1970
+ encoder.outputFormatting = .sortedKeys
+ return encoder
+ }()
+
+ private var lastJWT: (jwt: String, renewAt: Date)?
+
+ private var parsedKey: P256.Signing.PrivateKey?
+
+ nonisolated let key: ASCKey
+ init(key: ASCKey) {
+ self.key = key
+ }
+
+ private struct Header: Encodable {
+ let alg = "ES256"
+ let typ = "JWT"
+ let kid: String
+ }
+
+ private struct Payload: Encodable {
+ let aud = "appstoreconnect-v1"
+ let iss: String
+ let iat: Date
+ let exp: Date
+ }
+
+ private func encode(_ value: some Encodable) throws -> String {
+ try ASCJWTGenerator.encoder.encode(value).base64URLEncodedString()
+ }
+
+ private func getKey() throws -> P256.Signing.PrivateKey {
+ if let parsedKey { return parsedKey }
+
+ let key = try P256.Signing.PrivateKey(pemRepresentation: key.pem)
+ self.parsedKey = key
+
+ return key
+ }
+
+ func generate() throws -> String {
+ if let lastJWT, lastJWT.renewAt > Date() {
+ return lastJWT.jwt
+ }
+
+ let encodedHeader = try encode(Header(kid: key.id))
+
+ let issuedAt = Date()
+ let expiry = issuedAt + ASCJWTGenerator.ttl
+ let renewAt = expiry - ASCJWTGenerator.tolerance
+ let encodedPayload = try encode(Payload(iss: key.issuerID, iat: issuedAt, exp: expiry))
+
+ let body = "\(encodedHeader).\(encodedPayload)"
+ let signature = try getKey()
+ .signature(for: Data(body.utf8))
+ .rawRepresentation
+ .base64URLEncodedString()
+
+ let jwt = "\(body).\(signature)"
+ lastJWT = (jwt, renewAt)
+ return jwt
+ }
+}
+
+extension Data {
+ fileprivate func base64URLEncodedString() -> String {
+ self
+ .base64EncodedString()
+ .replacingOccurrences(of: "+", with: "-")
+ .replacingOccurrences(of: "/", with: "_")
+ .replacingOccurrences(of: "=", with: "")
+ }
+}
diff --git a/Sources/Supersign/DeveloperServices/App Groups/DeveloperServicesAssignAppGroupsOperation.swift b/Sources/Supersign/DeveloperServices/App Groups/DeveloperServicesAssignAppGroupsOperation.swift
index 274ec67..9581fc5 100644
--- a/Sources/Supersign/DeveloperServices/App Groups/DeveloperServicesAssignAppGroupsOperation.swift
+++ b/Sources/Supersign/DeveloperServices/App Groups/DeveloperServicesAssignAppGroupsOperation.swift
@@ -14,7 +14,11 @@ public struct DeveloperServicesAssignAppGroupsOperation: DeveloperServicesOperat
public let context: SigningContext
public let groupIDs: [DeveloperServicesAppGroup.GroupID]
public let appID: Components.Schemas.BundleId
- public init(
+ public let xcodeAuthData: XcodeAuthData
+
+ private let client: DeveloperServicesClient
+
+ public init?(
context: SigningContext,
groupIDs: [DeveloperServicesAppGroup.GroupID],
appID: Components.Schemas.BundleId
@@ -22,6 +26,11 @@ public struct DeveloperServicesAssignAppGroupsOperation: DeveloperServicesOperat
self.context = context
self.groupIDs = groupIDs
self.appID = appID
+
+ guard case .xcode(let authData) = context.auth else { return nil }
+ self.xcodeAuthData = authData
+
+ self.client = DeveloperServicesClient(authData: authData)
}
private func upsertAppGroup(
@@ -36,15 +45,18 @@ public struct DeveloperServicesAssignAppGroupsOperation: DeveloperServicesOperat
let groupID = ProvisioningIdentifiers.groupID(fromSanitized: sanitized, context: context)
let name = ProvisioningIdentifiers.groupName(fromSanitized: sanitized)
let request = DeveloperServicesAddAppGroupRequest(
- platform: context.platform, teamID: context.teamID, name: name, groupID: groupID
+ platform: .iOS,
+ teamID: xcodeAuthData.teamID,
+ name: name,
+ groupID: groupID
)
- group = try await context.client.send(request)
+ group = try await client.send(request)
}
- _ = try await context.client.send(
+ _ = try await client.send(
DeveloperServicesAssignAppGroupRequest(
- platform: context.platform,
- teamID: context.teamID,
+ platform: .iOS,
+ teamID: xcodeAuthData.teamID,
appIDID: appID.id,
groupID: group.id
)
@@ -54,8 +66,8 @@ public struct DeveloperServicesAssignAppGroupsOperation: DeveloperServicesOperat
}
public func perform() async throws -> [DeveloperServicesAppGroup.GroupID] {
- let existing = try await context.client.send(DeveloperServicesListAppGroupsRequest(
- platform: context.platform, teamID: context.teamID
+ let existing = try await client.send(DeveloperServicesListAppGroupsRequest(
+ platform: .iOS, teamID: xcodeAuthData.teamID
))
let sanitized = existing.map { (ProvisioningIdentifiers.sanitize(groupID: $0.groupID), $0) }
let dict = Dictionary(sanitized, uniquingKeysWith: { $1 })
diff --git a/Sources/Supersign/DeveloperServices/App IDs/DeveloperServicesAddAppOperation.swift b/Sources/Supersign/DeveloperServices/App IDs/DeveloperServicesAddAppOperation.swift
index 55d088c..7c92ebd 100644
--- a/Sources/Supersign/DeveloperServices/App IDs/DeveloperServicesAddAppOperation.swift
+++ b/Sources/Supersign/DeveloperServices/App IDs/DeveloperServicesAddAppOperation.swift
@@ -40,9 +40,11 @@ public struct DeveloperServicesAddAppOperation: DeveloperServicesOperation {
}
public let context: SigningContext
+ public let signingInfo: SigningInfo
public let root: URL
- public init(context: SigningContext, root: URL) {
+ public init(context: SigningContext, signingInfo: SigningInfo, root: URL) {
self.context = context
+ self.signingInfo = signingInfo
self.root = root
}
@@ -76,15 +78,76 @@ public struct DeveloperServicesAddAppOperation: DeveloperServicesOperation {
appID = try createResponse.created.body.json.data
}
- let request = DeveloperServicesUpdateAppIDRequest(
- platform: self.context.platform,
- teamID: self.context.teamID,
- appIDID: appID.id,
- entitlements: entitlements,
- additionalFeatures: [],
- isFree: isFreeTeam
+ let existingCapabilitiesList = try await context.developerAPIClient
+ .bundleIdsBundleIdCapabilitiesGetToManyRelated(.init(path: .init(id: appID.id)))
+ .ok.body.json.data
+ let existingCapabilities = [Components.Schemas.CapabilityType: Components.Schemas.BundleIdCapability](
+ existingCapabilitiesList.compactMap { cap in
+ (cap.attributes?.capabilityType).map { ($0, cap) }
+ },
+ uniquingKeysWith: { $1 }
+ )
+
+ let wantedCapabilitiesList = try entitlements.entitlements().compactMap(\.anyCapability)
+ let wantedCapabilities = [Components.Schemas.CapabilityType: [Components.Schemas.CapabilitySetting]](
+ wantedCapabilitiesList.map { ($0.capabilityType, $0.settings ?? []) },
+ uniquingKeysWith: { $1 }
)
- _ = try await context.client.send(request)
+
+ for (typ, cap) in existingCapabilities {
+ if let wantedSettings = wantedCapabilities[typ] {
+ if wantedSettings != (cap.attributes?.settings ?? []) {
+ _ = try await context.developerAPIClient.bundleIdCapabilitiesUpdateInstance(
+ path: .init(id: cap.id),
+ body: .json(
+ .init(
+ data: .init(
+ _type: .bundleIdCapabilities,
+ id: cap.id,
+ attributes: .init(
+ capabilityType: typ,
+ settings: wantedSettings
+ )
+ )
+ )
+ )
+ )
+ .ok
+ }
+ } else {
+ _ = try await context.developerAPIClient
+ .bundleIdCapabilitiesDeleteInstance(path: .init(id: cap.id))
+ .noContent
+ }
+ }
+ for (typ, settings) in wantedCapabilities {
+ guard existingCapabilities[typ] == nil else { continue }
+ _ = try await context.developerAPIClient.bundleIdCapabilitiesCreateInstance(
+ body: .json(.init(data: .init(
+ _type: .bundleIdCapabilities,
+ attributes: .init(
+ capabilityType: typ,
+ settings: settings
+ ),
+ relationships: .init(
+ bundleId: .init(
+ data: .init(
+ _type: .bundleIds,
+ id: appID.id
+ )
+ ),
+ // not public but required when using ds2 API
+ capability: .init(
+ data: .init(
+ _type: .capabilities,
+ id: typ
+ )
+ )
+ )
+ )))
+ )
+ .created.body
+ }
return appID
}
@@ -116,7 +179,7 @@ public struct DeveloperServicesAddAppOperation: DeveloperServicesOperation {
if isFreeTeam {
// re-assign rather than using updateEntitlements since the latter will
// retain unrecognized entitlements
- let filtered = try entitlements.entitlements().filter { type(of: $0).isFree }
+ let filtered = try entitlements.entitlements().filter { $0.anyCapability?.isFree != false }
entitlements = try Entitlements(entitlements: filtered)
}
} else {
@@ -126,8 +189,9 @@ public struct DeveloperServicesAddAppOperation: DeveloperServicesOperation {
let appID = try await upsertApp(bundleID: bundleID, entitlements: entitlements, isFreeTeam: isFreeTeam, appIDs: appIDs)
let newBundleID = appID.attributes!.identifier!
+ let teamID = try signingInfo.certificate.developerIdentity()
try entitlements.update(
- teamID: self.context.teamID,
+ teamID: .init(rawValue: teamID),
bundleID: newBundleID
)
// set get-task-allow to YES, required for dev certs
@@ -144,14 +208,15 @@ public struct DeveloperServicesAddAppOperation: DeveloperServicesOperation {
let groupsEntitlement = entitlementsArray[groupsIdx] as? AppGroupEntitlement {
let groups = groupsEntitlement.rawValue
- let newGroups = try await DeveloperServicesAssignAppGroupsOperation(
+ if let operation = DeveloperServicesAssignAppGroupsOperation(
context: self.context,
groupIDs: groups,
appID: appID
- ).perform()
-
- entitlementsArray[groupsIdx] = AppGroupEntitlement(rawValue: newGroups)
- try entitlements.setEntitlements(entitlementsArray)
+ ) {
+ let newGroups = try await operation.perform()
+ entitlementsArray[groupsIdx] = AppGroupEntitlement(rawValue: newGroups)
+ try entitlements.setEntitlements(entitlementsArray)
+ }
}
let mobileprovision = try await DeveloperServicesFetchProfileOperation(
@@ -167,11 +232,17 @@ public struct DeveloperServicesAddAppOperation: DeveloperServicesOperation {
}
private func getTeamIsFree() async throws -> Bool {
- let request = DeveloperServicesListTeamsRequest()
- let teams = try await context.client.send(request)
- guard let team = teams.first(where: { $0.id == self.context.teamID })
- else { throw Error.teamNotFound(self.context.teamID) }
- return team.isFree
+ switch context.auth {
+ case .appStoreConnect:
+ return false
+ case .xcode(let authData):
+ let client = DeveloperServicesClient(authData: authData)
+ let request = DeveloperServicesListTeamsRequest()
+ let teams = try await client.send(request)
+ guard let team = teams.first(where: { $0.id == authData.teamID })
+ else { throw Error.teamNotFound(authData.teamID) }
+ return team.isFree
+ }
}
// keyed by sanitized bundle ID
diff --git a/Sources/Supersign/DeveloperServices/App IDs/DeveloperServicesUpdateAppIDRequest.swift b/Sources/Supersign/DeveloperServices/App IDs/DeveloperServicesUpdateAppIDRequest.swift
deleted file mode 100644
index bc22ac1..0000000
--- a/Sources/Supersign/DeveloperServices/App IDs/DeveloperServicesUpdateAppIDRequest.swift
+++ /dev/null
@@ -1,63 +0,0 @@
-//
-// DeveloperServicesUpdateAppIDRequest.swift
-// Supercharge
-//
-// Created by Kabir Oberai on 24/07/19.
-// Copyright © 2019 Kabir Oberai. All rights reserved.
-//
-
-import Foundation
-
-public struct DeveloperServicesUpdateAppIDRequest: DeveloperServicesPlatformRequest {
-
- public typealias Value = EmptyResponse
-
- public let platform: DeveloperServicesPlatform
- public let teamID: DeveloperServicesTeam.ID
- public let appIDID: String
- public let entitlements: Entitlements
- public let additionalFeatures: [DeveloperServicesFeature]
- public let isFree: Bool
-
- var subAction: String { return "updateAppId" }
- var subParameters: [String: Any] {
- var parameters: [String: Any] = [
- "teamId": teamID.rawValue,
- "appIdId": appIDID
- ]
-
- var entitlements = entitlements
- try? entitlements.updateEntitlements {
- $0.removeAll {
- let type = Swift.type(of: $0)
- return !type.canList || (isFree && !type.isFree)
- }
- }
- parameters["entitlements"] = try? entitlements.plistValue()
-
- let entFeatures = (try? entitlements.entitlements().compactMap { $0.feature() }) ?? []
- let allFeatures = entFeatures + additionalFeatures
- if let features = try? DeveloperServicesFeatures(values: allFeatures).plistValue() as? [String: Any] {
- parameters.merge(features) { a, _ in a }
- }
-
- return parameters
- }
-
- public init(
- platform: DeveloperServicesPlatform,
- teamID: DeveloperServicesTeam.ID,
- appIDID: String,
- entitlements: Entitlements,
- additionalFeatures: [DeveloperServicesFeature],
- isFree: Bool
- ) {
- self.platform = platform
- self.teamID = teamID
- self.appIDID = appIDID
- self.entitlements = entitlements
- self.additionalFeatures = additionalFeatures
- self.isFree = isFree
- }
-
-}
diff --git a/Sources/Supersign/DeveloperServices/App IDs/Entitlements/DeveloperServicesCapability.swift b/Sources/Supersign/DeveloperServices/App IDs/Entitlements/DeveloperServicesCapability.swift
new file mode 100644
index 0000000..6742ea1
--- /dev/null
+++ b/Sources/Supersign/DeveloperServices/App IDs/Entitlements/DeveloperServicesCapability.swift
@@ -0,0 +1,130 @@
+//
+// DeveloperServicesFeatureTypes.swift
+// Supercharge
+//
+// Created by Kabir Oberai on 29/07/19.
+// Copyright © 2019 Kabir Oberai. All rights reserved.
+//
+
+import Foundation
+import DeveloperAPI
+
+public struct DeveloperServicesCapability: Sendable, Hashable {
+ public var capabilityType: Components.Schemas.CapabilityType
+ public var isFree: Bool
+ public var settings: [Components.Schemas.CapabilitySetting]?
+
+ public init(
+ _ capabilityType: Components.Schemas.CapabilityType,
+ isFree: Bool,
+ settings: [Components.Schemas.CapabilitySetting]? = nil
+ ) {
+ self.capabilityType = capabilityType
+ self.isFree = isFree
+ self.settings = settings
+ }
+}
+
+protocol EntitlementWithCapability: Entitlement {
+ var capability: DeveloperServicesCapability { get }
+}
+
+extension Entitlement {
+ var anyCapability: DeveloperServicesCapability? {
+ (self as? EntitlementWithCapability)?.capability
+ }
+}
+
+// MARK: - Special Features
+
+extension DataProtectionEntitlement: EntitlementWithCapability {
+ var capability: DeveloperServicesCapability {
+ let option: Components.Schemas.CapabilityOption.KeyPayload = switch self {
+ case .complete: .completeProtection
+ case .unlessOpen: .protectedUnlessOpen
+ case .untilFirstAuth: .protectedUntilFirstUserAuth
+ }
+ return DeveloperServicesCapability(
+ .dataProtection,
+ isFree: true,
+ settings: [
+ .init(
+ key: .dataProtectionPermissionLevel,
+ options: [.init(key: option)]
+ )
+ ]
+ )
+ }
+}
+
+// MARK: - Boolean Features
+
+// https://github.com/fastlane/fastlane/blob/master/spaceship/lib/spaceship/portal/app_service.rb
+
+extension AppGroupEntitlement: EntitlementWithCapability {
+ var capability: DeveloperServicesCapability {
+ // FIXME: Enable app groups on free accounts
+ // but we need to always assign only one group
+ DeveloperServicesCapability(.appGroups, isFree: false)
+ }
+}
+
+extension AssociatedDomainsEntitlement: EntitlementWithCapability {
+ var capability: DeveloperServicesCapability {
+ DeveloperServicesCapability(.associatedDomains, isFree: false)
+ }
+}
+
+extension HealthKitEntitlement: EntitlementWithCapability {
+ var capability: DeveloperServicesCapability {
+ DeveloperServicesCapability(.healthkit, isFree: true)
+ }
+}
+
+extension HomeKitEntitlement: EntitlementWithCapability {
+ var capability: DeveloperServicesCapability {
+ DeveloperServicesCapability(.homekit, isFree: true)
+ }
+}
+
+extension InterAppAudioEntitlement: EntitlementWithCapability {
+ var capability: DeveloperServicesCapability {
+ DeveloperServicesCapability(.interAppAudio, isFree: true)
+ }
+}
+
+extension MultipathEntitlement: EntitlementWithCapability {
+ var capability: DeveloperServicesCapability {
+ DeveloperServicesCapability(.multipath, isFree: false)
+ }
+}
+
+extension NetworkExtensionEntitlement: EntitlementWithCapability {
+ var capability: DeveloperServicesCapability {
+ DeveloperServicesCapability(.networkExtensions, isFree: false)
+ }
+}
+
+extension VPNConfigurationEntitlement: EntitlementWithCapability {
+ public var capability: DeveloperServicesCapability {
+ DeveloperServicesCapability(.personalVpn, isFree: false)
+ }
+}
+
+extension APSEnvironmentEntitlement: EntitlementWithCapability {
+ var capability: DeveloperServicesCapability {
+ DeveloperServicesCapability(.pushNotifications, isFree: false)
+ }
+}
+
+extension SiriKitEntitlement: EntitlementWithCapability {
+ var capability: DeveloperServicesCapability {
+ DeveloperServicesCapability(.sirikit, isFree: false)
+ }
+}
+
+extension WirelessAccessoryEntitlement: EntitlementWithCapability {
+ var capability: DeveloperServicesCapability {
+ DeveloperServicesCapability(.wirelessAccessoryConfiguration, isFree: true)
+ }
+}
diff --git a/Sources/Supersign/DeveloperServices/App IDs/Entitlements/Entitlement+DeveloperServicesFeature.swift b/Sources/Supersign/DeveloperServices/App IDs/Entitlements/Entitlement+DeveloperServicesFeature.swift
deleted file mode 100644
index c2341a7..0000000
--- a/Sources/Supersign/DeveloperServices/App IDs/Entitlements/Entitlement+DeveloperServicesFeature.swift
+++ /dev/null
@@ -1,38 +0,0 @@
-//
-// Entitlement+DeveloperServicesFeature.swift
-// Supersign
-//
-// Created by Kabir Oberai on 09/10/19.
-// Copyright © 2019 Kabir Oberai. All rights reserved.
-//
-
-import Foundation
-
-protocol BaseEntitlementWithFeature: Entitlement {
- func baseFeature() -> DeveloperServicesFeature
-}
-
-protocol EntitlementWithFeature: BaseEntitlementWithFeature {
- associatedtype Feature: DeveloperServicesFeature
- func typedFeature() -> Feature
-}
-extension EntitlementWithFeature {
- func baseFeature() -> DeveloperServicesFeature {
- return typedFeature()
- }
-}
-
-extension EntitlementWithFeature
- where Self: RawRepresentable,
- Feature: RawRepresentable,
- RawValue == Feature.RawValue {
- func typedFeature() -> Feature {
- return Feature(rawValue: rawValue)!
- }
-}
-
-public extension Entitlement {
- func feature() -> DeveloperServicesFeature? {
- return (self as? BaseEntitlementWithFeature)?.baseFeature()
- }
-}
diff --git a/Sources/Supersign/DeveloperServices/App IDs/Entitlements/EntitlementWithTeamOrBundleID.swift b/Sources/Supersign/DeveloperServices/App IDs/Entitlements/EntitlementWithTeamOrBundleID.swift
index 07572bc..850398c 100644
--- a/Sources/Supersign/DeveloperServices/App IDs/Entitlements/EntitlementWithTeamOrBundleID.swift
+++ b/Sources/Supersign/DeveloperServices/App IDs/Entitlements/EntitlementWithTeamOrBundleID.swift
@@ -9,23 +9,23 @@
import Foundation
protocol EntitlementWithTeamOrBundleID: Entitlement {
- init(teamID: DeveloperServicesTeam.ID, bundleID: String)
+ mutating func update(teamID: DeveloperServicesTeam.ID, bundleID: String)
}
extension ApplicationIdentifierEntitlement: EntitlementWithTeamOrBundleID {
- init(teamID: DeveloperServicesTeam.ID, bundleID: String) {
+ mutating func update(teamID: DeveloperServicesTeam.ID, bundleID: String) {
self.rawValue = "\(teamID.rawValue).\(bundleID)"
}
}
extension TeamIdentifierEntitlement: EntitlementWithTeamOrBundleID {
- init(teamID: DeveloperServicesTeam.ID, bundleID: String) {
+ mutating func update(teamID: DeveloperServicesTeam.ID, bundleID: String) {
self.rawValue = teamID.rawValue
}
}
extension KeychainAccessGroupsEntitlement: EntitlementWithTeamOrBundleID {
- init(teamID: DeveloperServicesTeam.ID, bundleID: String) {
+ mutating func update(teamID: DeveloperServicesTeam.ID, bundleID: String) {
rawValue = ["\(teamID.rawValue).\(bundleID)"]
}
}
@@ -33,13 +33,13 @@ extension KeychainAccessGroupsEntitlement: EntitlementWithTeamOrBundleID {
extension Entitlements {
public mutating func update(teamID: DeveloperServicesTeam.ID, bundleID: String) throws {
- let teamOrBundleIDTypes = EntitlementContainer.supportedTypes
- .compactMap { $0 as? EntitlementWithTeamOrBundleID.Type }
- let teamOrBundleIDSet = Set(teamOrBundleIDTypes.map(ObjectIdentifier.init))
-
try updateEntitlements { entitlements in
- entitlements.removeAll { teamOrBundleIDSet.contains(ObjectIdentifier(type(of: $0))) }
- entitlements += teamOrBundleIDTypes.map { $0.init(teamID: teamID, bundleID: bundleID) }
+ for entitlementIndex in entitlements.indices {
+ if var copy = entitlements[entitlementIndex] as? EntitlementWithTeamOrBundleID {
+ copy.update(teamID: teamID, bundleID: bundleID)
+ entitlements[entitlementIndex] = copy
+ }
+ }
}
}
diff --git a/Sources/Supersign/DeveloperServices/App IDs/Features/DeveloperServicesFeature.swift b/Sources/Supersign/DeveloperServices/App IDs/Features/DeveloperServicesFeature.swift
deleted file mode 100644
index c1f2086..0000000
--- a/Sources/Supersign/DeveloperServices/App IDs/Features/DeveloperServicesFeature.swift
+++ /dev/null
@@ -1,14 +0,0 @@
-//
-// DeveloperServicesFeature.swift
-// Supercharge
-//
-// Created by Kabir Oberai on 29/07/19.
-// Copyright © 2019 Kabir Oberai. All rights reserved.
-//
-
-import Foundation
-import ProtoCodable
-
-public protocol DeveloperServicesFeature: ProtoCodable, Sendable {
- static var identifier: String { get }
-}
diff --git a/Sources/Supersign/DeveloperServices/App IDs/Features/DeveloperServicesFeatureTypes.swift b/Sources/Supersign/DeveloperServices/App IDs/Features/DeveloperServicesFeatureTypes.swift
deleted file mode 100644
index c71a182..0000000
--- a/Sources/Supersign/DeveloperServices/App IDs/Features/DeveloperServicesFeatureTypes.swift
+++ /dev/null
@@ -1,273 +0,0 @@
-//
-// DeveloperServicesFeatureTypes.swift
-// Supercharge
-//
-// Created by Kabir Oberai on 29/07/19.
-// Copyright © 2019 Kabir Oberai. All rights reserved.
-//
-
-import Foundation
-import ProtoCodable
-
-// swiftlint:disable type_name
-
-extension DeveloperServicesFeatureContainer {
- static let supportedTypes: [ProtoCodable.Type] = [
- DeveloperServicesCloudKitFeature.self,
- DeveloperServicesDataProtectionFeature.self,
- DeveloperServicesAccessWifiFeature.self,
- DeveloperServicesAppGroupFeature.self,
- DeveloperServicesApplePayFeature.self,
- DeveloperServicesAssociatedDomainsFeature.self,
- DeveloperServicesClassKitFeature.self,
- DeveloperServicesAutoFillCredentialFeature.self,
- DeveloperServicesGameCenterFeature.self,
- DeveloperServicesHealthKitFeature.self,
- DeveloperServicesHomeKitFeature.self,
- DeveloperServicesHotspotFeature.self,
- DeveloperServicesCloudFeature.self,
- DeveloperServicesInAppPurchaseFeature.self,
- DeveloperServicesInterAppAudioFeature.self,
- DeveloperServicesMultipathFeature.self,
- DeveloperServicesNetworkExtensionFeature.self,
- DeveloperServicesNFCTagReadingFeature.self,
- DeveloperServicesPersonalVPNFeature.self,
- DeveloperServicesPassbookFeature.self,
- DeveloperServicesPushNotificationFeature.self,
- DeveloperServicesSiriKitFeature.self,
- DeveloperServicesVPNConfigurationFeature.self,
- DeveloperServicesWalletFeature.self,
- DeveloperServicesWirelessAccessoryFeature.self,
- ]
-}
-
-// MARK: - Special Features
-
-public enum DeveloperServicesCloudKitFeature: Int, DeveloperServicesFeature {
- public static let identifier = "cloudKitVersion"
-
- case xcode5Compatible = 1
- case cloudKit = 2
-}
-
-public enum DeveloperServicesDataProtectionFeature: String, DeveloperServicesFeature {
- public static let identifier = "dataProtection"
-
- case off = ""
- case complete
- case unlessOpen = "unlessopen"
- case untilFirstAuth = "untilfirstauth"
-}
-extension DataProtectionEntitlement: EntitlementWithFeature {
- func typedFeature() -> DeveloperServicesDataProtectionFeature {
- switch self {
- case .complete: return .complete
- case .unlessOpen: return .unlessOpen
- case .untilFirstAuth: return .untilFirstAuth
- }
- }
-}
-
-// MARK: - Boolean Features
-
-// https://github.com/fastlane/fastlane/blob/master/spaceship/lib/spaceship/portal/app_service.rb
-
-public struct DeveloperServicesAccessWifiFeature: DeveloperServicesFeature, RawRepresentable {
- public static let identifier = "AWEQ28MY3E"
-
- public let rawValue: Bool
- public init(rawValue: Bool) { self.rawValue = rawValue }
-}
-
-public struct DeveloperServicesAppGroupFeature: DeveloperServicesFeature, RawRepresentable {
- public static let identifier = "APG3427HIY"
-
- public let rawValue: Bool
- public init(rawValue: Bool) { self.rawValue = rawValue }
-}
-extension AppGroupEntitlement: EntitlementWithFeature {
- func typedFeature() -> DeveloperServicesAppGroupFeature {
- .init(rawValue: !rawValue.isEmpty)
- }
-}
-
-public struct DeveloperServicesApplePayFeature: DeveloperServicesFeature, RawRepresentable {
- public static let identifier = "OM633U5T5G"
-
- public let rawValue: Bool
- public init(rawValue: Bool) { self.rawValue = rawValue }
-}
-
-public struct DeveloperServicesAssociatedDomainsFeature: DeveloperServicesFeature, RawRepresentable {
- public static let identifier = "SKC3T5S89Y"
-
- public let rawValue: Bool
- public init(rawValue: Bool) { self.rawValue = rawValue }
-}
-extension AssociatedDomainsEntitlement: EntitlementWithFeature {
- func typedFeature() -> DeveloperServicesAssociatedDomainsFeature {
- .init(rawValue: true)
- }
-}
-
-public struct DeveloperServicesClassKitFeature: DeveloperServicesFeature, RawRepresentable {
- public static let identifier = "PKTJAN2017"
-
- public let rawValue: Bool
- public init(rawValue: Bool) { self.rawValue = rawValue }
-}
-
-public struct DeveloperServicesAutoFillCredentialFeature: DeveloperServicesFeature, RawRepresentable {
- public static let identifier = "CPEQ28MX4E"
-
- public let rawValue: Bool
- public init(rawValue: Bool) { self.rawValue = rawValue }
-}
-
-public struct DeveloperServicesGameCenterFeature: DeveloperServicesFeature, RawRepresentable {
- public static let identifier = "gameCenter"
-
- public let rawValue: Bool
- public init(rawValue: Bool) { self.rawValue = rawValue }
-}
-
-public struct DeveloperServicesHealthKitFeature: DeveloperServicesFeature, RawRepresentable {
- public static let identifier = "HK421J6T7P"
-
- public let rawValue: Bool
- public init(rawValue: Bool) { self.rawValue = rawValue }
-}
-extension HealthKitEntitlement: EntitlementWithFeature {
- typealias Feature = DeveloperServicesHealthKitFeature
-}
-
-public struct DeveloperServicesHomeKitFeature: DeveloperServicesFeature, RawRepresentable {
- public static let identifier = "homeKit"
-
- public let rawValue: Bool
- public init(rawValue: Bool) { self.rawValue = rawValue }
-}
-extension HomeKitEntitlement: EntitlementWithFeature {
- typealias Feature = DeveloperServicesHomeKitFeature
-}
-
-public struct DeveloperServicesHotspotFeature: DeveloperServicesFeature, RawRepresentable {
- public static let identifier = "HSC639VEI8"
-
- public let rawValue: Bool
- public init(rawValue: Bool) { self.rawValue = rawValue }
-}
-
-public struct DeveloperServicesCloudFeature: DeveloperServicesFeature, RawRepresentable {
- public static let identifier = "iCloud"
-
- public let rawValue: Bool
- public init(rawValue: Bool) { self.rawValue = rawValue }
-}
-
-public struct DeveloperServicesInAppPurchaseFeature: DeveloperServicesFeature, RawRepresentable {
- public static let identifier = "inAppPurchase"
-
- public let rawValue: Bool
- public init(rawValue: Bool) { self.rawValue = rawValue }
-}
-
-public struct DeveloperServicesInterAppAudioFeature: DeveloperServicesFeature, RawRepresentable {
- public static let identifier = "IAD53UNK2F"
-
- public let rawValue: Bool
- public init(rawValue: Bool) { self.rawValue = rawValue }
-}
-extension InterAppAudioEntitlement: EntitlementWithFeature {
- typealias Feature = DeveloperServicesInterAppAudioFeature
-}
-
-public struct DeveloperServicesMultipathFeature: DeveloperServicesFeature, RawRepresentable {
- public static let identifier = "MP49FN762P"
-
- public let rawValue: Bool
- public init(rawValue: Bool) { self.rawValue = rawValue }
-}
-extension MultipathEntitlement: EntitlementWithFeature {
- typealias Feature = DeveloperServicesMultipathFeature
-}
-
-public struct DeveloperServicesNetworkExtensionFeature: DeveloperServicesFeature, RawRepresentable {
- public static let identifier = "NWEXT04537"
-
- public let rawValue: Bool
- public init(rawValue: Bool) { self.rawValue = rawValue }
-}
-extension NetworkExtensionEntitlement: EntitlementWithFeature {
- typealias Feature = DeveloperServicesNetworkExtensionFeature
-}
-
-public struct DeveloperServicesNFCTagReadingFeature: DeveloperServicesFeature, RawRepresentable {
- public static let identifier = "NFCTRMAY17"
-
- public let rawValue: Bool
- public init(rawValue: Bool) { self.rawValue = rawValue }
-}
-
-public struct DeveloperServicesPersonalVPNFeature: DeveloperServicesFeature, RawRepresentable {
- public static let identifier = "V66P55NK2I"
-
- public let rawValue: Bool
- public init(rawValue: Bool) { self.rawValue = rawValue }
-}
-
-public struct DeveloperServicesPassbookFeature: DeveloperServicesFeature, RawRepresentable {
- public static let identifier = "passbook"
-
- public let rawValue: Bool
- public init(rawValue: Bool) { self.rawValue = rawValue }
-}
-
-public struct DeveloperServicesPushNotificationFeature: DeveloperServicesFeature, RawRepresentable {
- public static let identifier = "push"
-
- public let rawValue: Bool
- public init(rawValue: Bool) { self.rawValue = rawValue }
-}
-extension APSEnvironmentEntitlement: EntitlementWithFeature {
- func typedFeature() -> DeveloperServicesPushNotificationFeature {
- .init(rawValue: true)
- }
-}
-
-public struct DeveloperServicesSiriKitFeature: DeveloperServicesFeature, RawRepresentable {
- public static let identifier = "SI015DKUHP"
-
- public let rawValue: Bool
- public init(rawValue: Bool) { self.rawValue = rawValue }
-}
-extension SiriKitEntitlement: EntitlementWithFeature {
- typealias Feature = DeveloperServicesSiriKitFeature
-}
-
-public struct DeveloperServicesVPNConfigurationFeature: DeveloperServicesFeature, RawRepresentable {
- public static let identifier = "V66P55NK2I"
-
- public let rawValue: Bool
- public init(rawValue: Bool) { self.rawValue = rawValue }
-}
-extension VPNConfigurationEntitlement: EntitlementWithFeature {
- typealias Feature = DeveloperServicesVPNConfigurationFeature
-}
-
-public struct DeveloperServicesWalletFeature: DeveloperServicesFeature, RawRepresentable {
- public static let identifier = "pass"
-
- public let rawValue: Bool
- public init(rawValue: Bool) { self.rawValue = rawValue }
-}
-
-public struct DeveloperServicesWirelessAccessoryFeature: DeveloperServicesFeature, RawRepresentable {
- public static let identifier = "WC421J6T7P"
-
- public let rawValue: Bool
- public init(rawValue: Bool) { self.rawValue = rawValue }
-}
-extension WirelessAccessoryEntitlement: EntitlementWithFeature {
- typealias Feature = DeveloperServicesWirelessAccessoryFeature
-}
diff --git a/Sources/Supersign/DeveloperServices/App IDs/Features/DeveloperServicesFeatures.swift b/Sources/Supersign/DeveloperServices/App IDs/Features/DeveloperServicesFeatures.swift
deleted file mode 100644
index cc63f11..0000000
--- a/Sources/Supersign/DeveloperServices/App IDs/Features/DeveloperServicesFeatures.swift
+++ /dev/null
@@ -1,16 +0,0 @@
-//
-// DeveloperServicesFeatures.swift
-// Supercharge
-//
-// Created by Kabir Oberai on 19/09/19.
-// Copyright © 2019 Kabir Oberai. All rights reserved.
-//
-
-import Foundation
-import ProtoCodable
-
-struct DeveloperServicesFeatureContainer: ProtoCodableContainer {
- var value: DeveloperServicesFeature
-}
-
-typealias DeveloperServicesFeatures = ProtoCodableKeyValueContainer<DeveloperServicesFeatureContainer>
diff --git a/Sources/Supersign/DeveloperServices/Certificates/DeveloperServicesFetchCertificateOperation.swift b/Sources/Supersign/DeveloperServices/Certificates/DeveloperServicesFetchCertificateOperation.swift
index c3f4cc9..c273fd7 100644
--- a/Sources/Supersign/DeveloperServices/Certificates/DeveloperServicesFetchCertificateOperation.swift
+++ b/Sources/Supersign/DeveloperServices/Certificates/DeveloperServicesFetchCertificateOperation.swift
@@ -84,14 +84,14 @@ public struct DeveloperServicesFetchCertificateOperation: DeveloperServicesOpera
try await group.waitForAll()
}
let signingInfo = try await createCertificate()
- self.context.signingInfoManager[self.context.teamID] = signingInfo
+ self.context.signingInfoManager[self.context.auth.identityID] = signingInfo
return signingInfo
}
public func perform() async throws -> SigningInfo {
let certificates = try await context.developerAPIClient.certificatesGetCollection().ok.body.json.data
- guard let signingInfo = self.context.signingInfoManager[self.context.teamID] else {
+ guard let signingInfo = self.context.signingInfoManager[self.context.auth.identityID] else {
return try await self.replaceCertificates(certificates, requireConfirmation: true)
}
diff --git a/Sources/Supersign/DeveloperServices/DeveloperServices+OpenAPI.swift b/Sources/Supersign/DeveloperServices/DeveloperServices+OpenAPI.swift
index 4b919cb..9b36646 100644
--- a/Sources/Supersign/DeveloperServices/DeveloperServices+OpenAPI.swift
+++ b/Sources/Supersign/DeveloperServices/DeveloperServices+OpenAPI.swift
@@ -6,7 +6,7 @@ import OpenAPIURLSession
extension DeveloperAPIClient {
public init(
- middlewares: [any ClientMiddleware],
+ auth: DeveloperAPIAuthData,
httpFactory: HTTPClientFactory = defaultHTTPClientFactory
) {
self.init(
@@ -15,37 +15,61 @@ extension DeveloperAPIClient {
dateTranscoder: .iso8601WithFractionalSeconds
),
transport: httpFactory.makeClient().asOpenAPITransport,
- middlewares: middlewares
+ middlewares: [
+ auth.middleware
+ ]
)
}
+}
- public init(
- xcodeAPI: DeveloperAPIXcodeMiddleware,
- httpFactory: HTTPClientFactory = defaultHTTPClientFactory
- ) {
- self.init(
- middlewares: [xcodeAPI],
- httpFactory: httpFactory
- )
+public enum DeveloperAPIAuthData: Sendable {
+ case appStoreConnect(ASCKey)
+ case xcode(XcodeAuthData)
+
+ fileprivate var middleware: ClientMiddleware {
+ switch self {
+ case .appStoreConnect(let key):
+ DeveloperAPIASCAuthMiddleware(key: key)
+ case .xcode(let authData):
+ DeveloperAPIXcodeAuthMiddleware(authData: authData)
+ }
+ }
+
+ // A unique ID tied to this token
+ public var identityID: String {
+ switch self {
+ case .appStoreConnect(let key):
+ key.issuerID
+ case .xcode(let data):
+ data.teamID.rawValue
+ }
}
}
-public struct DeveloperAPIXcodeMiddleware: ClientMiddleware {
- public let loginToken: DeveloperServicesLoginToken
- public let deviceInfo: DeviceInfo
- public let teamID: String
- public let anisetteDataProvider: AnisetteDataProvider
+public struct XcodeAuthData: Sendable {
+ public var loginToken: DeveloperServicesLoginToken
+ public var deviceInfo: DeviceInfo
+ public var teamID: DeveloperServicesTeam.ID
+ public var anisetteDataProvider: AnisetteDataProvider
public init(
- anisetteDataProvider: AnisetteDataProvider,
loginToken: DeveloperServicesLoginToken,
deviceInfo: DeviceInfo,
- teamID: String
+ teamID: DeveloperServicesTeam.ID,
+ anisetteDataProvider: AnisetteDataProvider
) {
- self.anisetteDataProvider = anisetteDataProvider
self.loginToken = loginToken
self.deviceInfo = deviceInfo
self.teamID = teamID
+ self.anisetteDataProvider = anisetteDataProvider
+ }
+}
+
+public struct DeveloperAPIXcodeAuthMiddleware: ClientMiddleware {
+ public var authData: XcodeAuthData
+
+ public init(authData: XcodeAuthData) {
+ self.authData = authData
}
private static let baseURL = URL(string: "https://developerservices2.apple.com/services")!
@@ -78,15 +102,15 @@ public struct DeveloperAPIXcodeMiddleware: ClientMiddleware {
request.headerFields[.init(DeviceInfo.clientInfoKey)!] = """
<VirtualMac2,1> <macOS;15.1.1;24B91> <com.apple.AuthKit/1 (com.apple.dt.Xcode/23505)>
""" // deviceInfo.clientInfo.clientString
- request.headerFields[.init(DeviceInfo.deviceIDKey)!] = deviceInfo.deviceID
+ request.headerFields[.init(DeviceInfo.deviceIDKey)!] = authData.deviceInfo.deviceID
// GrandSlam authentication
request.headerFields[.init("X-Apple-App-Info")!] = AppTokenKey.xcode.rawValue
- request.headerFields[.init("X-Apple-I-Identity-Id")!] = loginToken.adsid
- request.headerFields[.init("X-Apple-GS-Token")!] = loginToken.token
+ request.headerFields[.init("X-Apple-I-Identity-Id")!] = authData.loginToken.adsid
+ request.headerFields[.init("X-Apple-GS-Token")!] = authData.loginToken.token
// Anisette
- let anisetteData = try await anisetteDataProvider.fetchAnisetteData()
+ let anisetteData = try await authData.anisetteDataProvider.fetchAnisetteData()
for (key, value) in anisetteData.dictionary {
request.headerFields[.init(key)!] = value
}
@@ -102,14 +126,14 @@ public struct DeveloperAPIXcodeMiddleware: ClientMiddleware {
let path = request.path ?? "/"
var components = URLComponents(string: path) ?? .init()
components.queryItems = (components.queryItems ?? []) + [
- URLQueryItem(name: "teamId", value: teamID)
+ URLQueryItem(name: "teamId", value: authData.teamID.rawValue)
]
let query = components.percentEncodedQuery ?? ""
components.query = nil
request.path = components.path
- let bodyData = try Self.queryEncoder.encode(["urlEncodedQueryParams": query])
+ let bodyData = try DeveloperAPIXcodeAuthMiddleware.queryEncoder.encode(["urlEncodedQueryParams": query])
body = HTTPBody(bodyData)
case .patch, .post:
// set .data.attributes.teamId = teamID
@@ -139,7 +163,7 @@ public struct DeveloperAPIXcodeMiddleware: ClientMiddleware {
workingAttributes = decodedAttributes
}
- workingAttributes["teamId"] = teamID
+ workingAttributes["teamId"] = authData.teamID.rawValue
workingData["attributes"] = workingAttributes
workingBody["data"] = workingData
@@ -151,7 +175,7 @@ public struct DeveloperAPIXcodeMiddleware: ClientMiddleware {
throw Errors.unrecognizedHTTPMethod(originalMethod.rawValue)
}
- var (response, responseBody) = try await next(request, body, Self.baseURL)
+ var (response, responseBody) = try await next(request, body, DeveloperAPIXcodeAuthMiddleware.baseURL)
if response.headerFields[.contentType] == "application/vnd.api+json" {
response.headerFields[.contentType] = "application/json"
@@ -165,3 +189,33 @@ public struct DeveloperAPIXcodeMiddleware: ClientMiddleware {
case malformedPayload(String)
}
}
+
+public struct DeveloperAPIASCAuthMiddleware: ClientMiddleware {
+ private var generator: ASCJWTGenerator
+
+ public var key: ASCKey {
+ get { generator.key }
+ set { generator = ASCJWTGenerator(key: newValue) }
+ }
+
+ public init(key: ASCKey) {
+ generator = ASCJWTGenerator(key: key)
+ }
+
+ public func intercept(
+ _ request: HTTPTypes.HTTPRequest,
+ body: OpenAPIRuntime.HTTPBody?,
+ baseURL: URL,
+ operationID: String,
+ next: @Sendable (
+ _ request: HTTPTypes.HTTPRequest,
+ _ body: OpenAPIRuntime.HTTPBody?,
+ _ baseURL: URL
+ ) async throws -> (HTTPTypes.HTTPResponse, OpenAPIRuntime.HTTPBody?)
+ ) async throws -> (HTTPTypes.HTTPResponse, OpenAPIRuntime.HTTPBody?) {
+ let jwt = try await generator.generate()
+ var request = request
+ request.headerFields[.authorization] = "Bearer \(jwt)"
+ return try await next(request, body, baseURL)
+ }
+}
diff --git a/Sources/Supersign/DeveloperServices/DeveloperServicesAPIVersion.swift b/Sources/Supersign/DeveloperServices/DeveloperServicesAPIVersion.swift
index 9cb0af3..e834110 100644
--- a/Sources/Supersign/DeveloperServices/DeveloperServicesAPIVersion.swift
+++ b/Sources/Supersign/DeveloperServices/DeveloperServicesAPIVersion.swift
@@ -17,7 +17,7 @@ public protocol DeveloperServicesAPIVersion: Sendable {
func decode<R: Decodable>(response: Data) throws -> R
}
-public struct DeveloperServicesAPIVersionOld: DeveloperServicesAPIVersion {
+public struct DeveloperServicesAPIVersionLegacy: DeveloperServicesAPIVersion {
public struct Error: LocalizedError {
public let code: Int
@@ -117,74 +117,3 @@ public struct DeveloperServicesAPIVersionOld: DeveloperServicesAPIVersion {
}
}
-
-public struct DeveloperServicesAPIVersionV1: DeveloperServicesAPIVersion {
-
- public struct UnknownError: Swift.Error {}
-
- public struct Error: LocalizedError, Decodable {
- public let status: String
- public let code: String
- public let title: String
- public let detail: String
-
- public var errorDescription: String? {
- "\(code) (\(status)): \(title)\n\(detail)"
- }
- }
-
- private struct Response<T: Decodable>: Decodable {
- private let errors: [Error]?
- private let data: T?
-
- fileprivate var result: Result<T, Swift.Error> {
- if let data = data { return .success(data) }
- let errors = self.errors ?? []
- switch errors.count {
- case 0: return .failure(UnknownError())
- case 1: return .failure(errors[0])
- default: return .failure(ErrorList(errors))
- }
- }
- }
-
- private static let decoder: JSONDecoder = {
- let decoder = JSONDecoder()
- let formatter = DateFormatter()
- formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
- formatter.calendar = Calendar(identifier: .iso8601)
- formatter.locale = Locale(identifier: "en_US_POSIX")
- decoder.dateDecodingStrategy = .formatted(formatter)
- return decoder
- }()
-
- public func url(forAction action: String) -> URL? {
- let urlString = "https://developerservices2.apple.com/services/v1/\(action)"
- return URL(string: urlString)
- }
-
- public let contentType = "application/vnd.api+json"
- public let accept = "application/vnd.api+json"
-
- public func body(withParameters parameters: [String: Any]) throws -> Data {
- var components = URLComponents()
- components.queryItems = parameters.map { URLQueryItem(name: $0, value: "\($1)") }
- let query = components.query ?? ""
- let dict = ["urlEncodedQueryParams": query]
- return try JSONSerialization.data(withJSONObject: dict)
- }
-
- public func decode<R: Decodable>(response: Data) throws -> R {
- // If `response` is empty and R is EmptyResponse, just return a new EmptyResponse
- // instead of crashing
- if let type = R.self as? EmptyResponse.Type {
- // swiftlint:disable:next force_cast
- return type.init() as! R
- } else {
- return try Self.decoder
- .decode(Response<R>.self, from: response)
- .result.get()
- }
- }
-
-}
diff --git a/Sources/Supersign/DeveloperServices/DeveloperServicesClient.swift b/Sources/Supersign/DeveloperServices/DeveloperServicesClient.swift
index 6d52b91..78535dd 100644
--- a/Sources/Supersign/DeveloperServices/DeveloperServicesClient.swift
+++ b/Sources/Supersign/DeveloperServices/DeveloperServicesClient.swift
@@ -8,7 +8,7 @@
import Foundation
-public final class DeveloperServicesClient: Sendable {
+public struct DeveloperServicesClient: Sendable {
public enum Error: LocalizedError {
case noData
@@ -70,6 +70,13 @@ public final class DeveloperServicesClient: Sendable {
self.httpClient = httpFactory.makeClient()
}
+ public init(authData: XcodeAuthData) {
+ self.loginToken = authData.loginToken
+ self.deviceInfo = authData.deviceInfo
+ self.anisetteDataProvider = authData.anisetteDataProvider
+ self.httpClient = defaultHTTPClientFactory.makeClient()
+ }
+
private func send<R: DeveloperServicesRequest>(
_ request: R,
anisetteData: AnisetteData
diff --git a/Sources/Supersign/DeveloperServices/DeveloperServicesProvisioningOperation.swift b/Sources/Supersign/DeveloperServices/DeveloperServicesProvisioningOperation.swift
index 198826b..c6daff1 100644
--- a/Sources/Supersign/DeveloperServices/DeveloperServicesProvisioningOperation.swift
+++ b/Sources/Supersign/DeveloperServices/DeveloperServicesProvisioningOperation.swift
@@ -48,7 +48,11 @@ public struct DeveloperServicesProvisioningOperation: DeveloperServicesOperation
).perform()
progress(2/3)
- let provisioningDict = try await DeveloperServicesAddAppOperation(context: context, root: app).perform()
+ let provisioningDict = try await DeveloperServicesAddAppOperation(
+ context: context,
+ signingInfo: signingInfo,
+ root: app
+ ).perform()
progress(3/3)
return .init(signingInfo: signingInfo, provisioningDict: provisioningDict)
diff --git a/Sources/Supersign/DeveloperServices/DeveloperServicesRequest.swift b/Sources/Supersign/DeveloperServices/DeveloperServicesRequest.swift
index bd43998..26d75ac 100644
--- a/Sources/Supersign/DeveloperServices/DeveloperServicesRequest.swift
+++ b/Sources/Supersign/DeveloperServices/DeveloperServicesRequest.swift
@@ -27,7 +27,7 @@ public protocol DeveloperServicesRequest: Sendable {
}
public extension DeveloperServicesRequest {
- var apiVersion: DeveloperServicesAPIVersion { DeveloperServicesAPIVersionOld() }
+ var apiVersion: DeveloperServicesAPIVersion { DeveloperServicesAPIVersionLegacy() }
var methodOverride: String? { nil }
func configure(urlRequest: inout HTTPRequest) {}
}
diff --git a/Sources/Supersign/Integration/SuperchargeInstaller.swift b/Sources/Supersign/Integration/SuperchargeInstaller.swift
index 5c5e12a..b858e07 100644
--- a/Sources/Supersign/Integration/SuperchargeInstaller.swift
+++ b/Sources/Supersign/Integration/SuperchargeInstaller.swift
@@ -81,9 +81,7 @@ public actor IntegratedInstaller {
let udid: String
let lookupMode: LookupMode
- let appleID: String
- let token: DeveloperServicesLoginToken
- let teamID: DeveloperServicesTeam.ID
+ let auth: DeveloperAPIAuthData
let configureDevice: Bool
let storage: KeyValueStorage
public weak var delegate: IntegratedInstallerDelegate?
@@ -142,18 +140,14 @@ public actor IntegratedInstaller {
public init(
udid: String,
lookupMode: LookupMode,
- appleID: String,
- token: DeveloperServicesLoginToken,
- teamID: DeveloperServicesTeam.ID,
+ auth: DeveloperAPIAuthData,
configureDevice: Bool,
storage: KeyValueStorage,
delegate: IntegratedInstallerDelegate
) {
self.udid = udid
self.lookupMode = lookupMode
- self.appleID = appleID
- self.token = token
- self.teamID = teamID
+ self.auth = auth
self.configureDevice = configureDevice
self.storage = storage
self.delegate = delegate
@@ -281,10 +275,6 @@ public actor IntegratedInstaller {
guard let appDir = payload.implicitContents.first(where: { $0.pathExtension == "app" })
else { throw Error.appExtractionFailed }
- guard let deviceInfo = DeviceInfo.current() else {
- throw Error.deviceInfoFetchFailed
- }
-
try await updateStage(to: "Logging in")
try await self.updateStage(to: "Preparing device")
@@ -311,23 +301,20 @@ public actor IntegratedInstaller {
} else {
nil
}
+ _ = pairingKeys
try await updateProgress(to: 1)
- let anisetteProvider = try ADIDataProvider.adiProvider(deviceInfo: deviceInfo, storage: storage)
- let client = DeveloperServicesClient(
- loginToken: token,
- deviceInfo: deviceInfo,
- anisetteProvider: anisetteProvider
- )
+// guard let deviceInfo = DeviceInfo.current() else {
+// throw Error.deviceInfoFetchFailed
+// }
+// let anisetteProvider = try ADIDataProvider.adiProvider(deviceInfo: deviceInfo, storage: storage)
let context = try SigningContext(
udid: udid,
deviceName: deviceName,
- teamID: teamID,
- client: client,
- signingInfoManager: KeyValueSigningInfoManager(storage: storage),
- platform: .iOS
+ auth: auth,
+ signingInfoManager: KeyValueSigningInfoManager(storage: storage)
)
let signer = Signer(context: context) { certs in
@@ -346,19 +333,21 @@ public actor IntegratedInstaller {
}
},
didProvision: { @Sendable [self] in
- if let pairingKeys = pairingKeys {
- let info = try context.signingInfoManager.info(forTeamID: context.teamID)
- try Superconfig(
- udid: udid,
- pairingKeys: pairingKeys,
- deviceInfo: deviceInfo,
- preferredTeamID: teamID.rawValue,
- preferredSigningInfo: info,
- appleID: appleID,
- provisioningData: anisetteProvider.provisioningData(),
- token: token
- ).save(inAppDir: appDir)
- }
+ // TODO: reintroduce Superconfig
+ _ = self
+// if let pairingKeys = pairingKeys {
+// let info = try context.signingInfoManager.info(forTeamID: context.teamID)
+// try Superconfig(
+// udid: udid,
+// pairingKeys: pairingKeys,
+// deviceInfo: deviceInfo,
+// preferredTeamID: teamID.rawValue,
+// preferredSigningInfo: info,
+// appleID: appleID,
+// provisioningData: anisetteProvider.provisioningData(),
+// token: token
+// ).save(inAppDir: appDir)
+// }
}
)
diff --git a/Sources/Supersign/Model/Entitlements/Entitlement.swift b/Sources/Supersign/Model/Entitlements/Entitlement.swift
index 2f695a7..de0c86f 100644
--- a/Sources/Supersign/Model/Entitlements/Entitlement.swift
+++ b/Sources/Supersign/Model/Entitlements/Entitlement.swift
@@ -11,11 +11,4 @@ import ProtoCodable
public protocol Entitlement: ProtoCodable, Sendable {
static var identifier: String { get }
- static var isFree: Bool { get }
- /// whether this entitlement should be included in developer services API requests
- static var canList: Bool { get }
-}
-
-public extension Entitlement {
- static var canList: Bool { return true }
}
diff --git a/Sources/Supersign/Model/Entitlements/EntitlementTypes.swift b/Sources/Supersign/Model/Entitlements/EntitlementTypes.swift
index 180531d..a316597 100644
--- a/Sources/Supersign/Model/Entitlements/EntitlementTypes.swift
+++ b/Sources/Supersign/Model/Entitlements/EntitlementTypes.swift
@@ -86,7 +86,6 @@ public struct AppGroupEntitlement: Entitlement, RawRepresentable {
public struct GetTaskAllowEntitlement: Entitlement, RawRepresentable {
public static let identifier = "get-task-allow"
public static let isFree = true
- public static let canList = false
public var rawValue: Bool
public init(rawValue: Bool) { self.rawValue = rawValue }
diff --git a/Sources/Supersign/Signer/SigningContext.swift b/Sources/Supersign/Signer/SigningContext.swift
index d793908..aa82051 100644
--- a/Sources/Supersign/Signer/SigningContext.swift
+++ b/Sources/Supersign/Signer/SigningContext.swift
@@ -13,38 +13,27 @@ public struct SigningContext: Sendable {
public let udid: String
public let deviceName: String
- public let teamID: DeveloperServicesTeam.ID
- public let client: DeveloperServicesClient
+
+ public let auth: DeveloperAPIAuthData
+
public let signingInfoManager: SigningInfoManager
- public let platform: DeveloperServicesPlatform
public let signerImpl: SignerImpl
public var developerAPIClient: DeveloperAPIClient {
- DeveloperAPIClient(
- xcodeAPI: DeveloperAPIXcodeMiddleware(
- anisetteDataProvider: client.anisetteDataProvider,
- loginToken: client.loginToken,
- deviceInfo: client.deviceInfo,
- teamID: teamID.rawValue
- )
- )
+ DeveloperAPIClient(auth: auth)
}
public init(
udid: String,
deviceName: String,
- teamID: DeveloperServicesTeam.ID,
- client: DeveloperServicesClient,
+ auth: DeveloperAPIAuthData,
signingInfoManager: SigningInfoManager,
- platform: DeveloperServicesPlatform = .current,
signerImpl: SignerImpl? = nil
) throws {
self.udid = udid
self.deviceName = deviceName
- self.teamID = teamID
- self.client = client
+ self.auth = auth
self.signingInfoManager = signingInfoManager
- self.platform = platform
self.signerImpl = try signerImpl ?? .first()
}
diff --git a/Sources/Supersign/Utilities/ProvisioningIdentifiers.swift b/Sources/Supersign/Utilities/ProvisioningIdentifiers.swift
index 67e8a1e..0a897a7 100644
--- a/Sources/Supersign/Utilities/ProvisioningIdentifiers.swift
+++ b/Sources/Supersign/Utilities/ProvisioningIdentifiers.swift
@@ -22,9 +22,7 @@ extension ProvisioningIdentifiers {
}
static func identifier(fromSanitized sanitized: String, context: SigningContext? = nil) -> String {
- // FIXME: Use something better than the team ID to generate the prefix. Maybe a random
- // UUID works as long as we can remember what the random UUID for each app was.
- let uuid = context?.teamID.rawValue ?? String(UUID().uuidString.split(separator: "-")[0])
+ let uuid = (context?.auth.identityID ?? UUID().uuidString).split(separator: "-")[0].uppercased()
return "\(Self.idPrefix)\(uuid).\(sanitized)"
}
diff --git a/Sources/Supersign/Utilities/SigningInfo.swift b/Sources/Supersign/Utilities/SigningInfo.swift
index 61ed034..8bdab12 100644
--- a/Sources/Supersign/Utilities/SigningInfo.swift
+++ b/Sources/Supersign/Utilities/SigningInfo.swift
@@ -15,17 +15,17 @@ public struct SigningInfo: Codable, Sendable {
}
public protocol SigningInfoManager: Sendable {
- func info(forTeamID teamID: DeveloperServicesTeam.ID) throws -> SigningInfo?
- func setInfo(_ info: SigningInfo?, forTeamID teamID: DeveloperServicesTeam.ID) throws
+ func info(forIdentityID identityID: String) throws -> SigningInfo?
+ func setInfo(_ info: SigningInfo?, forIdentityID identityID: String) throws
}
extension SigningInfoManager {
- subscript(teamID: DeveloperServicesTeam.ID) -> SigningInfo? {
+ subscript(identityID: String) -> SigningInfo? {
get {
- try? info(forTeamID: teamID)
+ try? info(forIdentityID: identityID)
}
nonmutating set {
- try? setInfo(newValue, forTeamID: teamID)
+ try? setInfo(newValue, forIdentityID: identityID)
}
}
}
@@ -35,13 +35,13 @@ public final class MemoryBackedSigningInfoManager: SigningInfoManager {
public init() {}
- public func info(forTeamID teamID: DeveloperServicesTeam.ID) throws -> SigningInfo? {
- infos[teamID.rawValue]
+ public func info(forIdentityID identityID: String) throws -> SigningInfo? {
+ infos[identityID]
}
- public func setInfo(_ info: SigningInfo?, forTeamID teamID: DeveloperServicesTeam.ID) throws {
+ public func setInfo(_ info: SigningInfo?, forIdentityID identityID: String) throws {
infos.withValue {
- $0[teamID.rawValue] = info
+ $0[identityID] = info
}
}
}
@@ -55,14 +55,14 @@ public struct KeyValueSigningInfoManager: SigningInfoManager {
self.storage = storage
}
- public func info(forTeamID teamID: DeveloperServicesTeam.ID) throws -> SigningInfo? {
- guard let data = try storage.data(forKey: teamID.rawValue)
+ public func info(forIdentityID identityID: String) throws -> SigningInfo? {
+ guard let data = try storage.data(forKey: identityID)
else { return nil }
return try decoder.decode(SigningInfo.self, from: data)
}
- public func setInfo(_ info: SigningInfo?, forTeamID teamID: DeveloperServicesTeam.ID) throws {
+ public func setInfo(_ info: SigningInfo?, forIdentityID identityID: String) throws {
let data = try encoder.encode(info)
- try storage.setData(data, forKey: teamID.rawValue)
+ try storage.setData(data, forKey: identityID)
}
}
diff --git a/Sources/SupersignCLISupport/AuthCommand.swift b/Sources/SupersignCLISupport/AuthCommand.swift
index 8ad5b58..8a422a2 100644
--- a/Sources/SupersignCLISupport/AuthCommand.swift
+++ b/Sources/SupersignCLISupport/AuthCommand.swift
@@ -1,22 +1,77 @@
import Foundation
import Supersign
import ArgumentParser
+import Crypto
+
+enum AuthMode: String, CaseIterable, CustomStringConvertible, ExpressibleByArgument {
+ case key
+ case password
+
+ var description: String {
+ switch self {
+ case .key: "Key (requires Apple Developer Program membership)"
+ case .password: "Password (works with any Apple ID but uses private APIs)"
+ }
+ }
+}
struct AuthOperation {
var username: String?
var password: String?
var logoutFromExisting: Bool
+ var mode: AuthMode? = nil
+
func run() async throws {
- if let token = try? AuthToken.saved() {
- if logoutFromExisting {
- try AuthToken.clear()
- } else {
- print("Logged in as \(token.appleID)")
- return
- }
+ if let token = try? AuthToken.saved(), !logoutFromExisting {
+ print("Logged in.\n\(token)")
+ return
+ }
+
+ let mode: AuthMode
+ if let existing = self.mode {
+ mode = existing
+ } else {
+ mode = try await Console.choose(
+ from: AuthMode.allCases,
+ onNoElement: { throw Console.Error("Mode selection is required") },
+ multiPrompt: "Select login mode",
+ formatter: \.description
+ )
+ }
+
+ let token = switch mode {
+ case .password:
+ try await logInWithPassword()
+ case .key:
+ try await logInWithKey()
}
+ try token.save()
+
+ print("Logged in")
+ }
+
+ private func logInWithKey() async throws -> AuthToken {
+ let id = try await Console.promptRequired("Key ID: ", existing: nil)
+ .trimmingCharacters(in: .whitespacesAndNewlines)
+
+ let issuerID = try await Console.promptRequired("Issuer ID: ", existing: nil)
+ .trimmingCharacters(in: .whitespacesAndNewlines)
+
+ let path = try await Console.promptRequired("Key path: ", existing: nil)
+ .trimmingCharacters(in: .whitespacesAndNewlines)
+ let pem = try String(decoding: Data(contentsOf: URL(fileURLWithPath: path)), as: UTF8.self)
+ do {
+ _ = try P256.Signing.PrivateKey(pemRepresentation: pem)
+ } catch {
+ throw Console.Error("Key is invalid: \(error)")
+ }
+
+ return AuthToken.appStoreConnect(.init(id: id, issuerID: issuerID, pem: pem))
+ }
+
+ private func logInWithPassword() async throws -> AuthToken {
let username = try await Console.promptRequired("Apple ID: ", existing: username)
let password: String
@@ -65,10 +120,13 @@ struct AuthOperation {
}
)
- let fullToken = AuthToken(appleID: username, teamID: team.id, dsToken: token)
- try fullToken.save()
-
- print("Logged in")
+ return AuthToken.xcode(.init(
+ appleID: username,
+ adsid: token.adsid,
+ token: token.token,
+ expiry: token.expiry,
+ teamID: team.id.rawValue
+ ))
}
}
@@ -80,12 +138,14 @@ struct AuthLoginCommand: AsyncParsableCommand {
@Option(name: [.short, .long], help: "Apple ID") var username: String?
@Option(name: [.short, .long]) var password: String?
+ @Option(name: [.short, .long]) var mode: AuthMode?
func run() async throws {
try await AuthOperation(
username: username,
password: password,
- logoutFromExisting: true
+ logoutFromExisting: true,
+ mode: mode
).run()
}
}
@@ -102,7 +162,7 @@ struct AuthLogoutCommand: AsyncParsableCommand {
"Reset 2-factor authentication data",
discussion: """
This resets the "pseudo-device" that Supersign presents itself as \
- when authenticating with Apple.
+ when authenticating with Apple using the password login mode.
Effectively, this means you will be prompted to complete 2-factor \
authentication again the next time you log in.
@@ -137,12 +197,7 @@ struct AuthStatusCommand: AsyncParsableCommand {
func run() async throws {
if let token = try? AuthToken.saved() {
- print("""
- Logged in.
- - Apple ID: \(token.appleID)
- - Team ID: \(token.teamID.rawValue)
- - Token expiry: \(token.expiry.formatted(.dateTime))
- """)
+ print("Logged in.\n\(token)")
} else {
print("Logged out")
}
diff --git a/Sources/SupersignCLISupport/AuthToken.swift b/Sources/SupersignCLISupport/AuthToken.swift
index 30d243d..8a50544 100644
--- a/Sources/SupersignCLISupport/AuthToken.swift
+++ b/Sources/SupersignCLISupport/AuthToken.swift
@@ -1,48 +1,42 @@
import Foundation
import Supersign
-struct AuthToken: Codable {
- var appleID: String
- var adsid: String
- var token: String
- var expiry: Date
-
- private var _teamID: String
- var teamID: DeveloperServicesTeam.ID {
- get { .init(rawValue: _teamID) }
- set { _teamID = newValue.rawValue }
+enum AuthToken: Codable, CustomStringConvertible {
+ struct Xcode: Codable {
+ var appleID: String
+ var adsid: String
+ var token: String
+ var expiry: Date
+ var teamID: String
}
- private enum CodingKeys: String, CodingKey {
- case appleID
- case _teamID = "teamID"
- case adsid
- case token
- case expiry
+ struct AppStoreConnect: Codable {
+ var id: String
+ var issuerID: String
+ var pem: String
}
-}
-extension AuthToken {
+ case appStoreConnect(AppStoreConnect)
+ case xcode(Xcode)
- init(
- appleID: String,
- teamID: DeveloperServicesTeam.ID,
- dsToken: DeveloperServicesLoginToken
- ) {
- self.appleID = appleID
- self._teamID = teamID.rawValue
- self.adsid = dsToken.adsid
- self.token = dsToken.token
- self.expiry = dsToken.expiry
+ var description: String {
+ switch self {
+ case .appStoreConnect(let data):
+ """
+ - ASC key ID: \(data.id)
+ - Issuer ID: \(data.issuerID)
+ """
+ case .xcode(let data):
+ """
+ - Apple ID: \(data.appleID)
+ - Team ID: \(data.teamID)
+ - Token expiry: \(data.expiry.formatted(.dateTime))
+ """
+ }
}
+}
- var dsToken: DeveloperServicesLoginToken {
- DeveloperServicesLoginToken(
- adsid: adsid,
- token: token,
- expiry: expiry
- )
- }
+extension AuthToken {
private static let encoder = JSONEncoder()
private static let decoder = JSONDecoder()
@@ -63,4 +57,26 @@ extension AuthToken {
try SupersignCLI.config.storage.setData(data, forKey: "SUPAuthToken")
}
+ func authData() throws -> DeveloperAPIAuthData {
+ switch self {
+ case .appStoreConnect(let data):
+ return .appStoreConnect(.init(id: data.id, issuerID: data.issuerID, pem: data.pem))
+ case .xcode(let data):
+ let deviceInfo = try DeviceInfo.fetch()
+ return .xcode(.init(
+ loginToken: DeveloperServicesLoginToken(
+ adsid: data.adsid,
+ token: data.token,
+ expiry: data.expiry
+ ),
+ deviceInfo: deviceInfo,
+ teamID: .init(rawValue: data.teamID),
+ anisetteDataProvider: try ADIDataProvider.adiProvider(
+ deviceInfo: deviceInfo,
+ storage: SupersignCLI.config.storage
+ )
+ ))
+ }
+ }
+
}
diff --git a/Sources/SupersignCLISupport/DSCommand.swift b/Sources/SupersignCLISupport/DSCommand.swift
index 4646876..4a6be52 100644
--- a/Sources/SupersignCLISupport/DSCommand.swift
+++ b/Sources/SupersignCLISupport/DSCommand.swift
@@ -1,6 +1,7 @@
import Foundation
import Supersign
import ArgumentParser
+import DeveloperAPI
struct DSTeamsListCommand: AsyncParsableCommand {
static let configuration = CommandConfiguration(
@@ -11,16 +12,10 @@ struct DSTeamsListCommand: AsyncParsableCommand {
func run() async throws {
let token = try AuthToken.saved()
- let deviceInfo = try DeviceInfo.fetch()
- let anisetteProvider = try ADIDataProvider.adiProvider(
- deviceInfo: deviceInfo, storage: SupersignCLI.config.storage
- )
-
- let client = DeveloperServicesClient(
- loginToken: token.dsToken,
- deviceInfo: deviceInfo,
- anisetteProvider: anisetteProvider
- )
+ guard case let .xcode(authData) = try token.authData() else {
+ throw Console.Error("This command requires password-based authentication")
+ }
+ let client = DeveloperServicesClient(authData: authData)
let teams: [DeveloperServicesTeam] = try await client.send(DeveloperServicesListTeamsRequest())
print(
teams.map {
diff --git a/Sources/SupersignCLISupport/DevCommand.swift b/Sources/SupersignCLISupport/DevCommand.swift
index e46c0d0..b4e6a8f 100644
--- a/Sources/SupersignCLISupport/DevCommand.swift
+++ b/Sources/SupersignCLISupport/DevCommand.swift
@@ -96,11 +96,6 @@ struct DevRunCommand: AsyncParsableCommand {
@OptionGroup var connectionOptions: ConnectionOptions
- @Option(
- name: .shortAndLong,
- help: "Preferred team ID"
- ) var team: String?
-
func run() async throws {
let output = try await PackOperation(options: packOptions).run()
@@ -113,9 +108,7 @@ struct DevRunCommand: AsyncParsableCommand {
let installer = IntegratedInstaller(
udid: client.udid,
lookupMode: .only(client.connectionType),
- appleID: token.appleID,
- token: token.dsToken,
- teamID: token.teamID,
+ auth: try token.authData(),
configureDevice: false,
storage: SupersignCLI.config.storage,
delegate: installDelegate
diff --git a/Sources/SupersignCLISupport/InstallCommand.swift b/Sources/SupersignCLISupport/InstallCommand.swift
index 1b563cd..b98b244 100644
--- a/Sources/SupersignCLISupport/InstallCommand.swift
+++ b/Sources/SupersignCLISupport/InstallCommand.swift
@@ -9,11 +9,6 @@ struct InstallCommand: AsyncParsableCommand {
abstract: "Install an ipa file to your device"
)
- @Option(
- name: .shortAndLong,
- help: "Preferred team ID"
- ) var team: String?
-
@OptionGroup var connectionOptions: ConnectionOptions
@Argument(
@@ -31,9 +26,7 @@ struct InstallCommand: AsyncParsableCommand {
let installer = IntegratedInstaller(
udid: client.udid,
lookupMode: .only(client.connectionType),
- appleID: token.appleID,
- token: token.dsToken,
- teamID: token.teamID,
+ auth: try token.authData(),
configureDevice: false,
storage: SupersignCLI.config.storage,
delegate: installDelegate
diff --git a/Sources/SupersignCLISupport/SuperchargeCommand.swift b/Sources/SupersignCLISupport/SuperchargeCommand.swift
index 2366fda..b65f78a 100644
--- a/Sources/SupersignCLISupport/SuperchargeCommand.swift
+++ b/Sources/SupersignCLISupport/SuperchargeCommand.swift
@@ -2,6 +2,8 @@ import Foundation
import Supersign
import ArgumentParser
+#if false
+
struct InstallSuperchargeCommand: AsyncParsableCommand {
static let configuration = CommandConfiguration(
commandName: "install",
@@ -59,3 +61,5 @@ struct SuperchargeCommand: ParsableCommand {
defaultSubcommand: InstallSuperchargeCommand.self
)
}
+
+#endif