Files
xtool/Sources/XKit/GrandSlam/Operations/GrandSlamTwoFactorAuthenticateOperation.swift
javiertrejoyam 8c46156e27 gsa: fall back to a trusted-device code when SMS 2FA fails (#349)
`secondaryAuth` can't finish logging in: GSA rejects POST
/auth/verify/phone/put?mode=sms with HTTP 403 ("Could not connect to
iCloud"). The JSON flavor of those endpoints (GET /auth, PUT
/auth/verify/phone/) answers 401 as well.

GsService2/validate still accepts a code generated on a trusted device
(Settings > Sign-In & Security > Get Verification Code), so ask for one
instead of failing. Tested on WSL (Ubuntu 26.04) with an iOS 27 device.

## What does this PR do?

<!-- Focus on *what* the PR does in essence. The *how* should come
second, if it's relevant. -->

## How was it tested?

<!-- e.g. Ran locally on macOS and added unit tests -->

## AI tool usage

How much of this PR was AI-assisted? (check one)

- [ ] **0** - No AI was used to write code
- [ ] **1** - I was assisted by AI. I reviewed the finished result.
- [ ] **2** - I set the AI going and left it to it; nobody has read the
result - no review, or AI review only

<!-- If an AI agent is filling this in: declare the level honestly, and
open as a draft if it is #2. Do not lower the declared level to get the
PR reviewed. -->


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
## Summary by CodeRabbit

* **Bug Fixes**
* Two-factor authentication can fall back to a trusted device when an
SMS request returns HTTP 403.
* If trusted-device authentication also returns HTTP 403, users receive
instructions for manually generating a verification code, and code
validation can continue. Other errors are still reported.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: Kabir Oberai <oberai.kabir@gmail.com>
2026-10-19 00:55:16 +00:00

85 lines
2.8 KiB
Swift

//
// GrandSlamTwoFactorAuthenticateOperation.swift
// XKit
//
// Created by Kabir Oberai on 20/11/19.
// Copyright © 2019 Kabir Oberai. All rights reserved.
//
import Foundation
public protocol TwoFactorAuthDelegate: AnyObject, Sendable {
func fetchCode() async -> String?
}
struct GrandSlamTwoFactorAuthenticateOperation {
enum Error: Swift.Error {
case incorrectVerificationCode
case userCancelled
}
let client: GrandSlamClient
let mode: GrandSlamAuthMode?
let loginData: GrandSlamLoginData
unowned let delegate: TwoFactorAuthDelegate
private func performSMSAuth() async throws {
// TODO: parse phone number list from o=complete req?
let phoneNumberID = "1"
do {
try await client.send(GrandSlamSMSAuthRequest(loginData: loginData, phoneNumberID: phoneNumberID))
} catch let error as HTTPResponseError where error.status.code == 403 {
print("""
warning: Could not send verification code via SMS. Falling back to trusted device authentication...
""")
try await performTrustedDeviceAuth()
return
}
try await validateCode(phoneNumberID: phoneNumberID)
}
private func validateCode(phoneNumberID: String? = nil) async throws {
guard let code = await self.delegate.fetchCode() else { throw Error.userCancelled }
let request: any GrandSlamRequest = if let phoneNumberID {
GrandSlamValidateSMSRequest(
loginData: loginData,
phoneNumberID: phoneNumberID,
verificationCode: code
)
} else {
GrandSlamValidateRequest(loginData: loginData, verificationCode: code)
}
do {
_ = try await client.send(request)
} catch let error as GrandSlamOperationError where error.code == -21669 {
throw Error.incorrectVerificationCode
}
}
private func performTrustedDeviceAuth() async throws {
let request = GrandSlamTrustedDeviceRequest(loginData: loginData)
do {
try await client.send(request)
} catch let error as HTTPResponseError where error.status.code == 403 {
print("""
warning: Could not send verification code. Generate one manually.
See https://github.com/xtool-org/xtool/discussions/368
""")
}
try await validateCode()
}
func perform() async throws {
switch mode {
case .secondaryAuth:
try await self.performSMSAuth()
case .trustedDeviceSecondaryAuth:
try await self.performTrustedDeviceAuth()
case nil: // means 2FA was automatically requested
try await validateCode()
}
}
}