Modern Apps git

xtool.git

Public
git clone https://git.maproj.org/xtool.git
appstore-distribution ▾

xtool.git / Sources / XToolSupport / AuthCommand.swift

AuthCommand.swift217 lines · 6.6 KiBRaw
1import Foundation
2import XKit
3import ArgumentParser
4import Crypto
5import Dependencies
6
7enum AuthMode: String, CaseIterable, CustomStringConvertible, ExpressibleByArgument {
8 case key
9 case password
10
11 var description: String {
12 switch self {
13 case .key: "API Key (requires paid Apple Developer Program membership)"
14 case .password: "Password (works with any Apple ID but uses private APIs)"
15 }
16 }
17}
18
19struct AuthOperation {
20 var username: String?
21 var password: String?
22 var logoutFromExisting: Bool
23
24 var mode: AuthMode?
25 var quiet = false
26
27 func run() async throws {
28 if let token = try? AuthToken.saved(), !logoutFromExisting {
29 if !quiet {
30 print("Logged in.\n\(token)")
31 }
32 return
33 }
34
35 let mode: AuthMode
36 if let existing = self.mode {
37 mode = existing
38 } else {
39 mode = try await Console.choose(
40 from: AuthMode.allCases,
41 onNoElement: { throw Console.Error("Mode selection is required") },
42 multiPrompt: "Select login mode",
43 formatter: \.description
44 )
45 }
46
47 let token = switch mode {
48 case .password:
49 try await logInWithPassword()
50 case .key:
51 try await logInWithKey()
52 }
53 try token.save()
54
55 print("Logged in.\n\(token)")
56 }
57
58 private func logInWithKey() async throws -> AuthToken {
59 let id = try await Console.promptRequired("Key ID: ", existing: nil)
60 .trimmingCharacters(in: .whitespacesAndNewlines)
61
62 let issuerID = try await Console.promptRequired("Issuer ID: ", existing: nil)
63 .trimmingCharacters(in: .whitespacesAndNewlines)
64
65 let path = try await Console.promptRequired("Key path: ", existing: nil)
66 .trimmingCharacters(in: .whitespacesAndNewlines)
67
68 let pem = try String(decoding: Data(contentsOf: URL(fileURLWithPath: path)), as: UTF8.self)
69 do {
70 _ = try P256.Signing.PrivateKey(pemRepresentation: pem)
71 } catch {
72 throw Console.Error("Key is invalid: \(error)")
73 }
74
75 return AuthToken.appStoreConnect(.init(id: id, issuerID: issuerID, pem: pem))
76 }
77
78 private func logInWithPassword() async throws -> AuthToken {
79 print("""
80 Heads up:
81 This works by emulating a virtual Mac to interact with Apple services.
82 We use a third-party service to create a randomized device ID token
83 (Anisette Data) but your credentials are only ever sent to Apple.
84 Still, consider using a secondary Apple ID since this is a private API.
85 """)
86
87 let username = try await Console.promptRequired("Apple ID: ", existing: username)
88
89 let password: String
90 if let existing = self.password {
91 password = existing
92 } else {
93 password = try await Console.getPassword("Password: ")
94 }
95 guard !password.isEmpty else {
96 throw Console.Error("Password cannot be empty.")
97 }
98
99 print("Logging in...")
100
101 let authDelegate = XToolAuthDelegate()
102 let manager = DeveloperServicesLoginManager()
103 let token = try await manager.logIn(
104 withUsername: username,
105 password: password,
106 twoFactorDelegate: authDelegate
107 )
108
109 let client = DeveloperServicesClient(loginToken: token)
110 let teams = try await client.send(DeveloperServicesListTeamsRequest())
111 let team = try await Console.choose(
112 from: teams,
113 onNoElement: {
114 throw Console.Error("No development teams found")
115 },
116 multiPrompt: "\nSelect a team",
117 formatter: {
118 "\($0.name) (\($0.id.rawValue))"
119 }
120 )
121
122 @Dependency(\.anisetteDataProvider) var anisetteProvider
123
124 return AuthToken.xcode(.init(
125 appleID: username,
126 adsid: token.adsid,
127 token: token.token,
128 expiry: token.expiry,
129 teamID: team.id.rawValue,
130 anisetteProviderID: anisetteProvider.providerID
131 ))
132 }
133}
134
135struct AuthLoginCommand: AsyncParsableCommand {
136 static let configuration = CommandConfiguration(
137 commandName: "login",
138 abstract: "Log in to Apple Developer Services"
139 )
140
141 @Option(name: [.short, .long], help: "Apple ID") var username: String?
142 @Option(name: [.short, .long]) var password: String?
143 @Option(name: [.short, .long]) var mode: AuthMode?
144
145 func run() async throws {
146 try await AuthOperation(
147 username: username,
148 password: password,
149 logoutFromExisting: true,
150 mode: mode
151 ).run()
152 }
153}
154
155struct AuthLogoutCommand: AsyncParsableCommand {
156 static let configuration = CommandConfiguration(
157 commandName: "logout",
158 abstract: "Log out of Apple Developer Services"
159 )
160
161 @Flag(
162 name: [.short, .customLong("reset-2fa")],
163 help: ArgumentHelp(
164 "Reset 2-factor authentication data",
165 discussion: """
166 This resets the "pseudo-device" that xtool presents itself as \
167 when authenticating with Apple using the password login mode.
168
169 Effectively, this means you will be prompted to complete 2-factor \
170 authentication again the next time you log in.
171 """
172 )
173 ) var reset2FA = false
174
175 func run() async throws {
176 if (try? AuthToken.saved()) != nil {
177 try AuthToken.clear()
178 print("Logged out")
179 } else {
180 print("Already logged out")
181 }
182
183 if reset2FA {
184 @Dependency(\.anisetteDataProvider) var anisetteProvider
185 await anisetteProvider.resetProvisioning()
186 print("Forgot device")
187 }
188 }
189}
190
191struct AuthStatusCommand: AsyncParsableCommand {
192 static let configuration = CommandConfiguration(
193 commandName: "status",
194 abstract: "Get Apple Developer Services auth status"
195 )
196
197 func run() async throws {
198 if let token = try? AuthToken.saved() {
199 print("Logged in.\n\(token)")
200 } else {
201 print("Logged out")
202 }
203 }
204}
205
206struct AuthCommand: AsyncParsableCommand {
207 static let configuration = CommandConfiguration(
208 commandName: "auth",
209 abstract: "Manage Apple Developer Services authentication",
210 subcommands: [
211 AuthLoginCommand.self,
212 AuthLogoutCommand.self,
213 AuthStatusCommand.self,
214 ],
215 defaultSubcommand: AuthLoginCommand.self
216 )
217}