-
Notifications
You must be signed in to change notification settings - Fork 172
Expand file tree
/
Copy pathClient.swift
More file actions
617 lines (547 loc) · 29.3 KB
/
Client.swift
File metadata and controls
617 lines (547 loc) · 29.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
import Foundation
import PromiseKit
import PMKFoundation
import Rainbow
import SRP
import Crypto
import CommonCrypto
public class Client {
private static let authTypes = ["sa", "hsa", "non-sa", "hsa2"]
public init() {}
public enum Error: Swift.Error, LocalizedError, Equatable {
case invalidSession
case invalidUsernameOrPassword(username: String)
case invalidPhoneNumberIndex(min: Int, max: Int, given: String?)
case incorrectSecurityCode
case unexpectedSignInResponse(statusCode: Int, message: String?)
case appleIDAndPrivacyAcknowledgementRequired
case serviceTemporarilyUnavailable
case noTrustedPhoneNumbers
case notAuthenticated
case invalidHashcash
case missingSecurityCodeInfo
case accountUsesHardwareKey
case srpInvalidPublicKey
case srpError(String)
case federatedAuthenticationRequired
public var errorDescription: String? {
switch self {
case .invalidUsernameOrPassword(let username):
return "Invalid username and password combination. Attempted to sign in with username \(username)."
case .appleIDAndPrivacyAcknowledgementRequired:
return "You must sign in to https://appstoreconnect.apple.com and acknowledge the Apple ID & Privacy agreement."
case .serviceTemporarilyUnavailable:
return "The service is temporarily unavailable. Please try again later."
case .invalidPhoneNumberIndex(let min, let max, let given):
return "Not a valid phone number index. Expecting a whole number between \(min)-\(max), but was given \(given ?? "nothing")."
case .noTrustedPhoneNumbers:
return "Your account doesn't have any trusted phone numbers, but they're required for two-factor authentication. See https://support.apple.com/en-ca/HT204915."
case .notAuthenticated:
return "You are already signed out"
case .invalidHashcash:
return "Could not create a hashcash for the session."
case .missingSecurityCodeInfo:
return "Expected security code info but didn't receive any."
case .accountUsesHardwareKey:
return "Account uses a hardware key for authentication but this is not supported yet."
case .federatedAuthenticationRequired:
return "This account uses federated authentication (e.g. Apple Business Manager). Browser-based login is required."
default:
return String(describing: self)
}
}
}
/// Use the olympus session endpoint to see if the existing session is still valid
public func validateSession() -> Promise<Void> {
return Current.network.dataTask(with: URLRequest.olympusSession)
.done { data, response in
guard
let jsonObject = (try? JSONSerialization.jsonObject(with: data)) as? [String: Any],
jsonObject["provider"] != nil
else { throw Error.invalidSession }
}
}
/// SRPLogin - Secure Remote Password
/// https://tools.ietf.org/html/rfc2945
/// Forked from https://github.com/adam-fowler/swift-srp that provides the algorithm
public func srpLogin(accountName: String, password: String) -> Promise<Void> {
var serviceKey: String!
let client = SRPClient(configuration: SRPConfiguration<SHA256>(.N2048))
let clientKeys = client.generateKeys()
let a = clientKeys.public
// Get the Service Key needed from olympus session needed in headers
return firstly { () -> Promise<(data: Data, response: URLResponse)> in
Current.network.dataTask(with: URLRequest.itcServiceKey)
}
.then { (data, _) -> Promise<(serviceKey: String, hashcash: String)> in
struct ServiceKeyResponse: Decodable {
let authServiceKey: String?
}
let response = try JSONDecoder().decode(ServiceKeyResponse.self, from: data)
serviceKey = response.authServiceKey
/// Load a hashcash of the account name
return self.loadHashcash(accountName: accountName, serviceKey: serviceKey).map { (serviceKey, $0) }
}
.then { (serviceKey, hashcash) -> Promise<(serviceKey: String, hashcash: String, data: Data)> in
/// Call the SRP /init endpoint to start the login
return Current.network.dataTask(with: URLRequest.SRPInit(serviceKey: serviceKey, a: Data(a.bytes).base64EncodedString(), accountName: accountName)).map { (serviceKey, hashcash, $0.data)}
}
.then { (serviceKey, hashcash, data) -> Promise<(data: Data, response: URLResponse)> in
let srpInit = try JSONDecoder().decode(ServerSRPInitResponse.self, from: data)
guard let decodedB = Data(base64Encoded: srpInit.b) else {
throw Error.srpInvalidPublicKey
}
guard let decodedSalt = Data(base64Encoded: srpInit.salt) else {
throw Error.srpInvalidPublicKey
}
let iterations = srpInit.iteration
do {
guard let encryptedPassword = self.pbkdf2(password: password, saltData: decodedSalt, keyByteCount: 32, prf: CCPseudoRandomAlgorithm(kCCPRFHmacAlgSHA256), rounds: iterations) else {
throw Error.srpInvalidPublicKey
}
let sharedSecret = try client.calculateSharedSecret(password: encryptedPassword, salt: [UInt8](decodedSalt), clientKeys: clientKeys, serverPublicKey: .init([UInt8](decodedB)))
let m1 = client.calculateClientProof(username: accountName, salt: [UInt8](decodedSalt), clientPublicKey: a, serverPublicKey: .init([UInt8](decodedB)), sharedSecret: .init(sharedSecret.bytes))
let m2 = client.calculateServerProof(clientPublicKey: a, clientProof: m1, sharedSecret: .init([UInt8](sharedSecret.bytes)))
/// call the /complete endpoint passing in the hashcash, servicekey, and the calculated proof.
return Current.network.dataTask(with: URLRequest.SRPComplete(serviceKey: serviceKey, hashcash: hashcash, accountName: accountName, c: srpInit.c, m1: Data(m1).base64EncodedString(), m2: Data(m2).base64EncodedString()))
} catch {
throw Error.srpError(error.localizedDescription)
}
}
.then { (data, response) -> Promise<Void> in
struct SignInResponse: Decodable {
let authType: String?
let serviceErrors: [ServiceError]?
struct ServiceError: Decodable, CustomStringConvertible {
let code: String
let message: String
var description: String {
return "\(code): \(message)"
}
}
}
let httpResponse = response as! HTTPURLResponse
do {
let responseBody = try JSONDecoder().decode(SignInResponse.self, from: data)
switch httpResponse.statusCode {
case 200:
return Current.network.dataTask(with: URLRequest.olympusSession).asVoid()
case 401:
throw Error.invalidUsernameOrPassword(username: accountName)
case 409:
return self.handleTwoStepOrFactor(data: data, response: response, serviceKey: serviceKey)
case 412 where Client.authTypes.contains(responseBody.authType ?? ""):
throw Error.appleIDAndPrivacyAcknowledgementRequired
default:
throw Error.unexpectedSignInResponse(statusCode: httpResponse.statusCode,
message: responseBody.serviceErrors?.map { $0.description }.joined(separator: ", "))
}
} catch DecodingError.dataCorrupted where httpResponse.statusCode == 503 {
throw Error.serviceTemporarilyUnavailable
} catch {
throw error
}
}
}
@available(*, deprecated, message: "Please use srpLogin")
public func login(accountName: String, password: String) -> Promise<Void> {
var serviceKey: String!
return firstly { () -> Promise<(data: Data, response: URLResponse)> in
Current.network.dataTask(with: URLRequest.itcServiceKey)
}
.then { (data, _) -> Promise<(serviceKey: String, hashcash: String)> in
struct ServiceKeyResponse: Decodable {
let authServiceKey: String?
}
let response = try JSONDecoder().decode(ServiceKeyResponse.self, from: data)
serviceKey = response.authServiceKey
return self.loadHashcash(accountName: accountName, serviceKey: serviceKey).map { (serviceKey, $0) }
}
.then { (serviceKey, hashcash) -> Promise<(data: Data, response: URLResponse)> in
return Current.network.dataTask(with: URLRequest.signIn(serviceKey: serviceKey, accountName: accountName, password: password, hashcash: hashcash))
}
.then { (data, response) -> Promise<Void> in
struct SignInResponse: Decodable {
let authType: String?
let serviceErrors: [ServiceError]?
struct ServiceError: Decodable, CustomStringConvertible {
let code: String
let message: String
var description: String {
return "\(code): \(message)"
}
}
}
let httpResponse = response as! HTTPURLResponse
do {
let responseBody = try JSONDecoder().decode(SignInResponse.self, from: data)
switch httpResponse.statusCode {
case 200:
return Current.network.dataTask(with: URLRequest.olympusSession).asVoid()
case 401:
throw Error.invalidUsernameOrPassword(username: accountName)
case 409:
return self.handleTwoStepOrFactor(data: data, response: response, serviceKey: serviceKey)
case 412 where Client.authTypes.contains(responseBody.authType ?? ""):
throw Error.appleIDAndPrivacyAcknowledgementRequired
default:
throw Error.unexpectedSignInResponse(statusCode: httpResponse.statusCode,
message: responseBody.serviceErrors?.map { $0.description }.joined(separator: ", "))
}
} catch DecodingError.dataCorrupted where httpResponse.statusCode == 503 {
throw Error.serviceTemporarilyUnavailable
} catch {
throw error
}
}
}
func handleTwoStepOrFactor(data: Data, response: URLResponse, serviceKey: String) -> Promise<Void> {
let httpResponse = response as! HTTPURLResponse
let sessionID = (httpResponse.allHeaderFields["X-Apple-ID-Session-Id"] as! String)
let scnt = (httpResponse.allHeaderFields["scnt"] as! String)
return firstly { () -> Promise<AuthOptionsResponse> in
return Current.network.dataTask(with: URLRequest.authOptions(serviceKey: serviceKey, sessionID: sessionID, scnt: scnt))
.map { try JSONDecoder().decode(AuthOptionsResponse.self, from: $0.data) }
}
.then { authOptions -> Promise<Void> in
switch authOptions.kind {
case .twoStep:
Current.logging.log("Received a response from Apple that indicates this account has two-step authentication enabled. xcodes currently only supports the newer two-factor authentication, though. Please consider upgrading to two-factor authentication, or open an issue on GitHub explaining why this isn't an option for you here: https://github.com/RobotsAndPencils/xcodes/issues/new".yellow)
return Promise.value(())
case .twoFactor:
return self.handleTwoFactor(serviceKey: serviceKey, sessionID: sessionID, scnt: scnt, authOptions: authOptions)
case .hardwareKey:
throw Error.accountUsesHardwareKey
case .unknown:
Current.logging.log("Received a response from Apple that indicates this account has two-step or two-factor authentication enabled, but xcodes is unsure how to handle this response:".red)
String(data: data, encoding: .utf8).map { Current.logging.log($0) }
return Promise.value(())
}
}
}
func handleTwoFactor(serviceKey: String, sessionID: String, scnt: String, authOptions: AuthOptionsResponse) -> Promise<Void> {
Current.logging.log("Two-factor authentication is enabled for this account.\n")
// SMS was sent automatically
if authOptions.smsAutomaticallySent {
return firstly { () throws -> Promise<(data: Data, response: URLResponse)> in
guard let securityCode = authOptions.securityCode else { throw Error.missingSecurityCodeInfo }
let code = self.promptForSMSSecurityCode(length: securityCode.length, for: authOptions.trustedPhoneNumbers!.first!)
return Current.network.dataTask(with: try URLRequest.submitSecurityCode(serviceKey: serviceKey, sessionID: sessionID, scnt: scnt, code: code))
.validateSecurityCodeResponse()
}
.then { (data, response) -> Promise<Void> in
self.updateSession(serviceKey: serviceKey, sessionID: sessionID, scnt: scnt)
}
// SMS wasn't sent automatically because user needs to choose a phone to send to
} else if authOptions.canFallBackToSMS {
return handleWithPhoneNumberSelection(authOptions: authOptions, serviceKey: serviceKey, sessionID: sessionID, scnt: scnt)
// Code is shown on trusted devices
} else {
let securityCodeLength: Int = authOptions.securityCode?.length ?? 0
let code = Current.shell.readLine("""
Enter "sms" without quotes to exit this prompt and choose a phone number to send an SMS security code to.
Enter the \(securityCodeLength) digit code from one of your trusted devices:
""") ?? ""
if code == "sms" {
return handleWithPhoneNumberSelection(authOptions: authOptions, serviceKey: serviceKey, sessionID: sessionID, scnt: scnt)
}
return firstly {
Current.network.dataTask(with: try URLRequest.submitSecurityCode(serviceKey: serviceKey, sessionID: sessionID, scnt: scnt, code: .device(code: code)))
.validateSecurityCodeResponse()
}
.then { (data, response) -> Promise<Void> in
self.updateSession(serviceKey: serviceKey, sessionID: sessionID, scnt: scnt)
}
}
}
func updateSession(serviceKey: String, sessionID: String, scnt: String) -> Promise<Void> {
return Current.network.dataTask(with: URLRequest.trust(serviceKey: serviceKey, sessionID: sessionID, scnt: scnt))
.then { (data, response) -> Promise<Void> in
Current.network.dataTask(with: URLRequest.olympusSession).asVoid()
}
}
func selectPhoneNumberInteractively(from trustedPhoneNumbers: [AuthOptionsResponse.TrustedPhoneNumber]) -> Promise<AuthOptionsResponse.TrustedPhoneNumber> {
return firstly { () throws -> Guarantee<AuthOptionsResponse.TrustedPhoneNumber> in
Current.logging.log("Trusted phone numbers:")
trustedPhoneNumbers.enumerated().forEach { (index, phoneNumber) in
Current.logging.log("\(index + 1): \(phoneNumber.numberWithDialCode)")
}
let possibleSelectionNumberString = Current.shell.readLine("Select a trusted phone number to receive a code via SMS: ")
guard
let selectionNumberString = possibleSelectionNumberString,
let selectionNumber = Int(selectionNumberString) ,
trustedPhoneNumbers.indices.contains(selectionNumber - 1)
else {
throw Error.invalidPhoneNumberIndex(min: 1, max: trustedPhoneNumbers.count, given: possibleSelectionNumberString)
}
return .value(trustedPhoneNumbers[selectionNumber - 1])
}
.recover { error throws -> Promise<AuthOptionsResponse.TrustedPhoneNumber> in
guard case Error.invalidPhoneNumberIndex = error else { throw error }
Current.logging.log("\(error.localizedDescription)\n".red)
return self.selectPhoneNumberInteractively(from: trustedPhoneNumbers)
}
}
func promptForSMSSecurityCode(length: Int, for trustedPhoneNumber: AuthOptionsResponse.TrustedPhoneNumber) -> SecurityCode {
let code = Current.shell.readLine("Enter the \(length) digit code sent to \(trustedPhoneNumber.numberWithDialCode): ") ?? ""
return .sms(code: code, phoneNumberId: trustedPhoneNumber.id)
}
func handleWithPhoneNumberSelection(authOptions: AuthOptionsResponse, serviceKey: String, sessionID: String, scnt: String) -> Promise<Void> {
return firstly { () throws -> Promise<AuthOptionsResponse.TrustedPhoneNumber> in
// I don't think this should ever be nil or empty, because 2FA requires at least one trusted phone number,
// but if it is nil or empty it's better to inform the user so they can try to address it instead of crashing.
guard let trustedPhoneNumbers = authOptions.trustedPhoneNumbers, trustedPhoneNumbers.isEmpty == false else {
throw Error.noTrustedPhoneNumbers
}
return selectPhoneNumberInteractively(from: trustedPhoneNumbers)
}
.then { trustedPhoneNumber in
Current.network.dataTask(with: try URLRequest.requestSecurityCode(serviceKey: serviceKey, sessionID: sessionID, scnt: scnt, trustedPhoneID: trustedPhoneNumber.id))
.map { _ in
guard let securityCodeLength = authOptions.securityCode?.length else { throw Error.missingSecurityCodeInfo }
return self.promptForSMSSecurityCode(length: securityCodeLength, for: trustedPhoneNumber)
}
}
.then { code in
Current.network.dataTask(with: try URLRequest.submitSecurityCode(serviceKey: serviceKey, sessionID: sessionID, scnt: scnt, code: code))
.validateSecurityCodeResponse()
}
.then { (data, response) -> Promise<Void> in
self.updateSession(serviceKey: serviceKey, sessionID: sessionID, scnt: scnt)
}
}
public func checkFederation(accountName: String, serviceKey: String) -> Promise<FederationResponse> {
return Current.network.dataTask(with: URLRequest.checkFederation(serviceKey: serviceKey, accountName: accountName))
.map { data, _ in
try JSONDecoder().decode(FederationResponse.self, from: data)
}
}
/// Fetches the service key and checks whether the account uses federated authentication.
/// Call this before prompting for a password to avoid unnecessary password prompts for federated accounts.
public func checkIsFederated(accountName: String) -> Promise<FederationResponse> {
return firstly { () -> Promise<(data: Data, response: URLResponse)> in
Current.network.dataTask(with: URLRequest.itcServiceKey)
}
.then { (data, _) -> Promise<FederationResponse> in
struct ServiceKeyResponse: Decodable {
let authServiceKey: String?
}
let response = try JSONDecoder().decode(ServiceKeyResponse.self, from: data)
guard let serviceKey = response.authServiceKey else {
return .value(FederationResponse(federated: false))
}
return self.checkFederation(accountName: accountName, serviceKey: serviceKey)
}
}
/// Validates a federated authentication token by calling Apple's /federate/validate endpoint.
/// This exchanges the token and relay state from the IdP callback URL for session cookies.
public func validateFederatedToken(widgetKey: String, token: String, relayState: String) -> Promise<Void> {
return Current.network.dataTask(with: URLRequest.federateValidate(widgetKey: widgetKey, token: token, relayState: relayState))
.then { (data, response) -> Promise<Void> in
let httpResponse = response as! HTTPURLResponse
switch httpResponse.statusCode {
case 200...299:
return Current.network.dataTask(with: URLRequest.olympusSession).asVoid()
case 409:
// May need 2FA even after federated login
let serviceKey = widgetKey
return self.handleTwoStepOrFactor(data: data, response: response, serviceKey: serviceKey)
default:
throw Error.unexpectedSignInResponse(statusCode: httpResponse.statusCode, message: nil)
}
}
}
// Fixes issue https://github.com/RobotsAndPencils/XcodesApp/issues/360
// On 2023-02-23, Apple added a custom implementation of hashcash to their auth flow
// Without this addition, Apple ID's would get set to locked
func loadHashcash(accountName: String, serviceKey: String) -> Promise<String> {
return firstly{ () -> Promise<(data: Data, response: URLResponse)> in
Current.network.dataTask(with: try URLRequest.federate(account: accountName, serviceKey: serviceKey))
}
.then { (_ response) -> Promise<String> in
guard let urlResponse = response.response as? HTTPURLResponse else {
throw Client.Error.invalidSession
}
guard let bitString = urlResponse.allHeaderFields["X-Apple-HC-Bits"] as? String, let bits = UInt(bitString) else {
throw Client.Error.invalidHashcash
}
guard let challenge = urlResponse.allHeaderFields["X-Apple-HC-Challenge"] as? String else {
throw Client.Error.invalidHashcash
}
guard let hashcash = Hashcash().mint(resource: challenge, bits: bits) else {
throw Client.Error.invalidHashcash
}
return .value(hashcash)
}
}
private func sha256(data : Data) -> Data {
var hash = [UInt8](repeating: 0, count: Int(CC_SHA256_DIGEST_LENGTH))
data.withUnsafeBytes {
_ = CC_SHA256($0.baseAddress, CC_LONG(data.count), &hash)
}
return Data(hash)
}
private func pbkdf2(password: String, saltData: Data, keyByteCount: Int, prf: CCPseudoRandomAlgorithm, rounds: Int) -> Data? {
guard let passwordData = password.data(using: .utf8) else { return nil }
let hashedPasswordData = sha256(data: passwordData)
var derivedKeyData = Data(repeating: 0, count: keyByteCount)
let derivedCount = derivedKeyData.count
let derivationStatus: Int32 = derivedKeyData.withUnsafeMutableBytes { derivedKeyBytes in
let keyBuffer: UnsafeMutablePointer<UInt8> =
derivedKeyBytes.baseAddress!.assumingMemoryBound(to: UInt8.self)
return saltData.withUnsafeBytes { saltBytes -> Int32 in
let saltBuffer: UnsafePointer<UInt8> = saltBytes.baseAddress!.assumingMemoryBound(to: UInt8.self)
return hashedPasswordData.withUnsafeBytes { hashedPasswordBytes -> Int32 in
let passwordBuffer: UnsafePointer<UInt8> = hashedPasswordBytes.baseAddress!.assumingMemoryBound(to: UInt8.self)
return CCKeyDerivationPBKDF(
CCPBKDFAlgorithm(kCCPBKDF2),
passwordBuffer,
hashedPasswordData.count,
saltBuffer,
saltData.count,
prf,
UInt32(rounds),
keyBuffer,
derivedCount)
}
}
}
return derivationStatus == kCCSuccess ? derivedKeyData : nil
}
}
public extension Promise where T == (data: Data, response: URLResponse) {
func validateSecurityCodeResponse() -> Promise<T> {
validate()
.recover { error -> Promise<(data: Data, response: URLResponse)> in
switch error {
case PMKHTTPError.badStatusCode(let code, _, _):
if code == 401 {
throw Client.Error.incorrectSecurityCode
} else {
throw error
}
default:
throw error
}
}
}
}
struct AuthOptionsResponse: Decodable {
let trustedPhoneNumbers: [TrustedPhoneNumber]?
let trustedDevices: [TrustedDevice]?
let securityCode: SecurityCodeInfo?
let noTrustedDevices: Bool?
let serviceErrors: [ServiceError]?
let fsaChallenge: FSAChallenge?
var kind: Kind {
if trustedDevices != nil {
return .twoStep
} else if trustedPhoneNumbers != nil {
return .twoFactor
} else if fsaChallenge != nil {
return .hardwareKey
} else {
return .unknown
}
}
// One time with a new testing account I had a response where noTrustedDevices was nil, but the account didn't have any trusted devices.
// This should have been a situation where an SMS security code was sent automatically.
// This resolved itself either after some time passed, or by signing into appleid.apple.com with the account.
// Not sure if it's worth explicitly handling this case or if it'll be really rare.
var canFallBackToSMS: Bool {
noTrustedDevices == true
}
var smsAutomaticallySent: Bool {
trustedPhoneNumbers?.count == 1 && canFallBackToSMS
}
struct TrustedPhoneNumber: Decodable {
let id: Int
let numberWithDialCode: String
}
struct TrustedDevice: Decodable {
let id: String
let name: String
let modelName: String
}
struct SecurityCodeInfo: Decodable {
let length: Int
let tooManyCodesSent: Bool
let tooManyCodesValidated: Bool
let securityCodeLocked: Bool
let securityCodeCooldown: Bool
}
struct FSAChallenge: Decodable {
let challenge: String
let keyHandles: [String]
let rpId: String
let allowedCredentials: String
}
enum Kind {
case twoStep, twoFactor, hardwareKey, unknown
}
}
public struct ServiceError: Decodable, Equatable {
let code: String
let message: String
}
enum SecurityCode {
case device(code: String)
case sms(code: String, phoneNumberId: Int)
var urlPathComponent: String {
switch self {
case .device: return "trusteddevice"
case .sms: return "phone"
}
}
}
public struct ServerSRPInitResponse: Decodable {
let iteration: Int
let salt: String
let b: String
let c: String
}
public struct FederationResponse: Decodable, Equatable {
public let federated: Bool
public let showFederatedIdpConfirmation: Bool?
public let federatedIdpRequest: FederatedIdpRequest?
public let federatedAuthIntro: FederatedAuthIntro?
public init(federated: Bool, showFederatedIdpConfirmation: Bool? = nil, federatedIdpRequest: FederatedIdpRequest? = nil, federatedAuthIntro: FederatedAuthIntro? = nil) {
self.federated = federated
self.showFederatedIdpConfirmation = showFederatedIdpConfirmation
self.federatedIdpRequest = federatedIdpRequest
self.federatedAuthIntro = federatedAuthIntro
}
/// Builds the full IdP URL with request parameters as query items.
public var idpURL: URL? {
guard let idpRequest = federatedIdpRequest else { return nil }
var components = URLComponents(string: idpRequest.idPUrl)
components?.queryItems = idpRequest.requestParams.map { key, value in
URLQueryItem(name: key, value: value)
}
return components?.url
}
}
public struct FederatedIdpRequest: Decodable, Equatable {
public let idPUrl: String
public let requestParams: [String: String]
public let httpMethod: String?
public init(idPUrl: String, requestParams: [String: String], httpMethod: String?) {
self.idPUrl = idPUrl
self.requestParams = requestParams
self.httpMethod = httpMethod
}
}
public struct FederatedAuthIntro: Decodable, Equatable {
public let orgName: String?
public let idpName: String?
public let idpUrl: String?
public let orgType: String?
public let accountManagementUrl: String?
public init(orgName: String?, idpName: String?, idpUrl: String?, orgType: String?, accountManagementUrl: String?) {
self.orgName = orgName
self.idpName = idpName
self.idpUrl = idpUrl
self.orgType = orgType
self.accountManagementUrl = accountManagementUrl
}
}