PhoneAuthProvider.swift 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655
  1. // Copyright 2023 Google LLC
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. import FirebaseCore
  15. import Foundation
  16. /// A concrete implementation of `AuthProvider` for phone auth providers.
  17. ///
  18. /// This class is available on iOS only.
  19. @available(iOS 13, tvOS 13, macOS 10.15, macCatalyst 13, watchOS 7, *)
  20. @objc(FIRPhoneAuthProvider) open class PhoneAuthProvider: NSObject {
  21. /// A string constant identifying the phone identity provider.
  22. @objc public static let id = "phone"
  23. private static let recaptchaVersion = "RECAPTCHA_ENTERPRISE"
  24. private static let clientType = "CLIENT_TYPE_IOS"
  25. private static let fakeCaptchaResponse = "NO_RECAPTCHA"
  26. #if os(iOS)
  27. /// Returns an instance of `PhoneAuthProvider` for the default `Auth` object.
  28. @objc(provider) open class func provider() -> PhoneAuthProvider {
  29. return PhoneAuthProvider(auth: Auth.auth())
  30. }
  31. /// Returns an instance of `PhoneAuthProvider` for the provided `Auth` object.
  32. /// - Parameter auth: The auth object to associate with the phone auth provider instance.
  33. @objc(providerWithAuth:)
  34. open class func provider(auth: Auth) -> PhoneAuthProvider {
  35. return PhoneAuthProvider(auth: auth)
  36. }
  37. /// Starts the phone number authentication flow by sending a verification code to the
  38. /// specified phone number.
  39. ///
  40. /// Possible error codes:
  41. /// * `AuthErrorCodeCaptchaCheckFailed` - Indicates that the reCAPTCHA token obtained by
  42. /// the Firebase Auth is invalid or has expired.
  43. /// * `AuthErrorCodeQuotaExceeded` - Indicates that the phone verification quota for this
  44. /// project has been exceeded.
  45. /// * `AuthErrorCodeInvalidPhoneNumber` - Indicates that the phone number provided is invalid.
  46. /// * `AuthErrorCodeMissingPhoneNumber` - Indicates that a phone number was not provided.
  47. /// - Parameter phoneNumber: The phone number to be verified.
  48. /// - Parameter uiDelegate: An object used to present the SFSafariViewController. The object is
  49. /// retained by this method until the completion block is executed.
  50. /// - Parameter completion: The callback to be invoked when the verification flow is finished.
  51. @objc(verifyPhoneNumber:UIDelegate:completion:)
  52. open func verifyPhoneNumber(_ phoneNumber: String,
  53. uiDelegate: AuthUIDelegate? = nil,
  54. completion: ((_: String?, _: Error?) -> Void)?) {
  55. verifyPhoneNumber(phoneNumber,
  56. uiDelegate: uiDelegate,
  57. multiFactorSession: nil,
  58. completion: completion)
  59. }
  60. /// Verify ownership of the second factor phone number by the current user.
  61. /// - Parameter phoneNumber: The phone number to be verified.
  62. /// - Parameter uiDelegate: An object used to present the SFSafariViewController. The object is
  63. /// retained by this method until the completion block is executed.
  64. /// - Parameter multiFactorSession: A session to identify the MFA flow. For enrollment, this
  65. /// identifies the user trying to enroll. For sign-in, this identifies that the user already
  66. /// passed the first factor challenge.
  67. /// - Parameter completion: The callback to be invoked when the verification flow is finished.
  68. @objc(verifyPhoneNumber:UIDelegate:multiFactorSession:completion:)
  69. open func verifyPhoneNumber(_ phoneNumber: String,
  70. uiDelegate: AuthUIDelegate? = nil,
  71. multiFactorSession: MultiFactorSession? = nil,
  72. completion: ((_: String?, _: Error?) -> Void)?) {
  73. Task {
  74. do {
  75. let verificationID = try await verifyPhoneNumber(
  76. phoneNumber,
  77. uiDelegate: uiDelegate,
  78. multiFactorSession: multiFactorSession
  79. )
  80. await MainActor.run {
  81. completion?(verificationID, nil)
  82. }
  83. } catch {
  84. await MainActor.run {
  85. completion?(nil, error)
  86. }
  87. }
  88. }
  89. }
  90. /// Verify ownership of the second factor phone number by the current user.
  91. /// - Parameter phoneNumber: The phone number to be verified.
  92. /// - Parameter uiDelegate: An object used to present the SFSafariViewController. The object is
  93. /// retained by this method until the completion block is executed.
  94. /// - Parameter multiFactorSession: A session to identify the MFA flow. For enrollment, this
  95. /// identifies the user trying to enroll. For sign-in, this identifies that the user already
  96. /// passed the first factor challenge.
  97. /// - Returns: The verification ID
  98. @available(iOS 13, tvOS 13, macOS 10.15, watchOS 8, *)
  99. open func verifyPhoneNumber(_ phoneNumber: String,
  100. uiDelegate: AuthUIDelegate? = nil,
  101. multiFactorSession: MultiFactorSession? = nil) async throws
  102. -> String {
  103. guard AuthWebUtils.isCallbackSchemeRegistered(forCustomURLScheme: callbackScheme,
  104. urlTypes: auth.mainBundleUrlTypes) else {
  105. fatalError(
  106. "Please register custom URL scheme \(callbackScheme) in the app's Info.plist file."
  107. )
  108. }
  109. if let verificationID = try await internalVerify(phoneNumber: phoneNumber,
  110. uiDelegate: uiDelegate,
  111. multiFactorSession: multiFactorSession) {
  112. return verificationID
  113. } else {
  114. throw AuthErrorUtils.invalidVerificationIDError(message: "Invalid verification ID")
  115. }
  116. }
  117. /// Verify ownership of the second factor phone number by the current user.
  118. /// - Parameter multiFactorInfo: The phone multi factor whose number need to be verified.
  119. /// - Parameter uiDelegate: An object used to present the SFSafariViewController. The object is
  120. /// retained by this method until the completion block is executed.
  121. /// - Parameter multiFactorSession: A session to identify the MFA flow. For enrollment, this
  122. /// identifies the user trying to enroll. For sign-in, this identifies that the user already
  123. /// passed the first factor challenge.
  124. /// - Parameter completion: The callback to be invoked when the verification flow is finished.
  125. @objc(verifyPhoneNumberWithMultiFactorInfo:UIDelegate:multiFactorSession:completion:)
  126. open func verifyPhoneNumber(with multiFactorInfo: PhoneMultiFactorInfo,
  127. uiDelegate: AuthUIDelegate? = nil,
  128. multiFactorSession: MultiFactorSession?,
  129. completion: ((_: String?, _: Error?) -> Void)?) {
  130. Task {
  131. do {
  132. let verificationID = try await verifyPhoneNumber(
  133. with: multiFactorInfo,
  134. uiDelegate: uiDelegate,
  135. multiFactorSession: multiFactorSession
  136. )
  137. await MainActor.run {
  138. completion?(verificationID, nil)
  139. }
  140. } catch {
  141. await MainActor.run {
  142. completion?(nil, error)
  143. }
  144. }
  145. }
  146. }
  147. /// Verify ownership of the second factor phone number by the current user.
  148. /// - Parameter multiFactorInfo: The phone multi factor whose number need to be verified.
  149. /// - Parameter uiDelegate: An object used to present the SFSafariViewController. The object is
  150. /// retained by this method until the completion block is executed.
  151. /// - Parameter multiFactorSession: A session to identify the MFA flow. For enrollment, this
  152. /// identifies the user trying to enroll. For sign-in, this identifies that the user already
  153. /// passed the first factor challenge.
  154. /// - Returns: The verification ID.
  155. @available(iOS 13, tvOS 13, macOS 10.15, watchOS 8, *)
  156. open func verifyPhoneNumber(with multiFactorInfo: PhoneMultiFactorInfo,
  157. uiDelegate: AuthUIDelegate? = nil,
  158. multiFactorSession: MultiFactorSession?) async throws -> String {
  159. multiFactorSession?.multiFactorInfo = multiFactorInfo
  160. return try await verifyPhoneNumber(multiFactorInfo.phoneNumber,
  161. uiDelegate: uiDelegate,
  162. multiFactorSession: multiFactorSession)
  163. }
  164. /// Creates an `AuthCredential` for the phone number provider identified by the
  165. /// verification ID and verification code.
  166. ///
  167. /// - Parameter verificationID: The verification ID obtained from invoking
  168. /// verifyPhoneNumber:completion:
  169. /// - Parameter verificationCode: The verification code obtained from the user.
  170. /// - Returns: The corresponding phone auth credential for the verification ID and verification
  171. /// code provided.
  172. @objc(credentialWithVerificationID:verificationCode:)
  173. open func credential(withVerificationID verificationID: String,
  174. verificationCode: String) -> PhoneAuthCredential {
  175. return PhoneAuthCredential(withProviderID: PhoneAuthProvider.id,
  176. verificationID: verificationID,
  177. verificationCode: verificationCode)
  178. }
  179. private func internalVerify(phoneNumber: String,
  180. uiDelegate: AuthUIDelegate?,
  181. multiFactorSession: MultiFactorSession? = nil) async throws
  182. -> String? {
  183. guard !phoneNumber.isEmpty else {
  184. throw AuthErrorUtils.missingPhoneNumberError(message: nil)
  185. }
  186. guard let manager = auth.notificationManager else {
  187. throw AuthErrorUtils.notificationNotForwardedError()
  188. }
  189. guard await manager.checkNotificationForwarding() else {
  190. throw AuthErrorUtils.notificationNotForwardedError()
  191. }
  192. let recaptchaVerifier = AuthRecaptchaVerifier.shared(auth: auth)
  193. try await recaptchaVerifier.retrieveRecaptchaConfig(forceRefresh: true)
  194. switch recaptchaVerifier.enablementStatus(forProvider: .phone) {
  195. case .off:
  196. return try await verifyClAndSendVerificationCode(
  197. toPhoneNumber: phoneNumber,
  198. retryOnInvalidAppCredential: true,
  199. multiFactorSession: multiFactorSession,
  200. uiDelegate: uiDelegate
  201. )
  202. case .audit:
  203. return try await verifyClAndSendVerificationCodeWithRecaptcha(
  204. toPhoneNumber: phoneNumber,
  205. retryOnInvalidAppCredential: true,
  206. multiFactorSession: multiFactorSession,
  207. uiDelegate: uiDelegate,
  208. recaptchaVerifier: recaptchaVerifier
  209. )
  210. case .enforce:
  211. return try await verifyClAndSendVerificationCodeWithRecaptcha(
  212. toPhoneNumber: phoneNumber,
  213. retryOnInvalidAppCredential: false,
  214. multiFactorSession: multiFactorSession,
  215. uiDelegate: uiDelegate,
  216. recaptchaVerifier: recaptchaVerifier
  217. )
  218. }
  219. }
  220. func verifyClAndSendVerificationCodeWithRecaptcha(toPhoneNumber phoneNumber: String,
  221. retryOnInvalidAppCredential: Bool,
  222. uiDelegate: AuthUIDelegate?,
  223. recaptchaVerifier: AuthRecaptchaVerifier) async throws
  224. -> String? {
  225. let request = SendVerificationCodeRequest(phoneNumber: phoneNumber,
  226. codeIdentity: CodeIdentity.empty,
  227. requestConfiguration: auth
  228. .requestConfiguration)
  229. do {
  230. try await recaptchaVerifier.injectRecaptchaFields(
  231. request: request,
  232. provider: .phone,
  233. action: .sendVerificationCode
  234. )
  235. let response = try await auth.backend.call(with: request)
  236. return response.verificationID
  237. } catch {
  238. return try await handleVerifyErrorWithRetry(error: error,
  239. phoneNumber: phoneNumber,
  240. retryOnInvalidAppCredential: retryOnInvalidAppCredential,
  241. multiFactorSession: nil,
  242. uiDelegate: uiDelegate,
  243. auditFallback: true)
  244. }
  245. }
  246. /// Starts the flow to verify the client via silent push notification.
  247. /// - Parameter retryOnInvalidAppCredential: Whether or not the flow should be retried if an
  248. /// AuthErrorCodeInvalidAppCredential error is returned from the backend.
  249. /// - Parameter phoneNumber: The phone number to be verified.
  250. /// - Parameter callback: The callback to be invoked on the global work queue when the flow is
  251. /// finished.
  252. private func verifyClAndSendVerificationCode(toPhoneNumber phoneNumber: String,
  253. retryOnInvalidAppCredential: Bool,
  254. uiDelegate: AuthUIDelegate?,
  255. auditFallback: Bool = false) async throws
  256. -> String? {
  257. let codeIdentity = try await verifyClient(withUIDelegate: uiDelegate)
  258. let request = SendVerificationCodeRequest(phoneNumber: phoneNumber,
  259. codeIdentity: codeIdentity,
  260. requestConfiguration: auth
  261. .requestConfiguration)
  262. if auditFallback {
  263. request.injectRecaptchaFields(
  264. recaptchaResponse: PhoneAuthProvider.fakeCaptchaResponse,
  265. recaptchaVersion: PhoneAuthProvider.recaptchaVersion
  266. )
  267. }
  268. do {
  269. let response = try await auth.backend.call(with: request)
  270. return response.verificationID
  271. } catch {
  272. return try await handleVerifyErrorWithRetry(
  273. error: error,
  274. phoneNumber: phoneNumber,
  275. retryOnInvalidAppCredential: retryOnInvalidAppCredential,
  276. multiFactorSession: nil,
  277. uiDelegate: uiDelegate,
  278. auditFallback: auditFallback
  279. )
  280. }
  281. }
  282. /// Starts the flow to verify the client via silent push notification. This is used in both
  283. /// .Audit and .Enforce mode
  284. /// - Parameter retryOnInvalidAppCredential: Whether or not the flow should be retried if an
  285. /// AuthErrorCodeInvalidAppCredential error is returned from the backend.
  286. /// - Parameter phoneNumber: The phone number to be verified.
  287. private func verifyClAndSendVerificationCodeWithRecaptcha(toPhoneNumber phoneNumber: String,
  288. retryOnInvalidAppCredential: Bool,
  289. multiFactorSession session: MultiFactorSession?,
  290. uiDelegate: AuthUIDelegate?,
  291. recaptchaVerifier: AuthRecaptchaVerifier) async throws
  292. -> String? {
  293. if let settings = auth.settings,
  294. settings.isAppVerificationDisabledForTesting {
  295. let request = SendVerificationCodeRequest(
  296. phoneNumber: phoneNumber,
  297. codeIdentity: CodeIdentity.empty,
  298. requestConfiguration: auth.requestConfiguration
  299. )
  300. let response = try await auth.backend.call(with: request)
  301. return response.verificationID
  302. }
  303. guard let session else {
  304. return try await verifyClAndSendVerificationCodeWithRecaptcha(
  305. toPhoneNumber: phoneNumber,
  306. retryOnInvalidAppCredential: retryOnInvalidAppCredential,
  307. uiDelegate: uiDelegate,
  308. recaptchaVerifier: recaptchaVerifier
  309. )
  310. }
  311. let startMFARequestInfo = AuthProtoStartMFAPhoneRequestInfo(phoneNumber: phoneNumber,
  312. codeIdentity: CodeIdentity.empty)
  313. do {
  314. if let idToken = session.idToken {
  315. let request = StartMFAEnrollmentRequest(idToken: idToken,
  316. enrollmentInfo: startMFARequestInfo,
  317. requestConfiguration: auth.requestConfiguration)
  318. try await recaptchaVerifier.injectRecaptchaFields(
  319. request: request,
  320. provider: .phone,
  321. action: .mfaSmsEnrollment
  322. )
  323. let response = try await auth.backend.call(with: request)
  324. return response.phoneSessionInfo?.sessionInfo
  325. } else {
  326. let request = StartMFASignInRequest(MFAPendingCredential: session.mfaPendingCredential,
  327. MFAEnrollmentID: session.multiFactorInfo?.uid,
  328. signInInfo: startMFARequestInfo,
  329. requestConfiguration: auth.requestConfiguration)
  330. try await recaptchaVerifier.injectRecaptchaFields(
  331. request: request,
  332. provider: .phone,
  333. action: .mfaSmsSignIn
  334. )
  335. let response = try await auth.backend.call(with: request)
  336. return response.responseInfo.sessionInfo
  337. }
  338. } catch {
  339. // For Audit fallback only after rCE check failed
  340. return try await handleVerifyErrorWithRetry(
  341. error: error,
  342. phoneNumber: phoneNumber,
  343. retryOnInvalidAppCredential: retryOnInvalidAppCredential,
  344. multiFactorSession: session,
  345. uiDelegate: uiDelegate,
  346. auditFallback: true
  347. )
  348. }
  349. }
  350. /// Starts the flow to verify the client via silent push notification.
  351. /// This method is called in Audit fallback flow with "NO_RECAPTCHA" fake token and Off flow
  352. /// - Parameter retryOnInvalidAppCredential: Whether or not the flow should be retried if an
  353. /// AuthErrorCodeInvalidAppCredential error is returned from the backend.
  354. /// - Parameter phoneNumber: The phone number to be verified.
  355. private func verifyClAndSendVerificationCode(toPhoneNumber phoneNumber: String,
  356. retryOnInvalidAppCredential: Bool,
  357. multiFactorSession session: MultiFactorSession?,
  358. uiDelegate: AuthUIDelegate?,
  359. auditFallback: Bool = false) async throws
  360. -> String? {
  361. if let settings = auth.settings,
  362. settings.isAppVerificationDisabledForTesting {
  363. let request = SendVerificationCodeRequest(
  364. phoneNumber: phoneNumber,
  365. codeIdentity: CodeIdentity.empty,
  366. requestConfiguration: auth.requestConfiguration
  367. )
  368. let response = try await auth.backend.call(with: request)
  369. return response.verificationID
  370. }
  371. guard let session else {
  372. // Phone MFA flow
  373. return try await verifyClAndSendVerificationCode(
  374. toPhoneNumber: phoneNumber,
  375. retryOnInvalidAppCredential: retryOnInvalidAppCredential,
  376. uiDelegate: uiDelegate,
  377. auditFallback: auditFallback
  378. )
  379. }
  380. // MFA flows
  381. let codeIdentity = try await verifyClient(withUIDelegate: uiDelegate)
  382. let startMFARequestInfo = AuthProtoStartMFAPhoneRequestInfo(phoneNumber: phoneNumber,
  383. codeIdentity: codeIdentity)
  384. if auditFallback {
  385. startMFARequestInfo.injectRecaptchaFields(
  386. recaptchaResponse: PhoneAuthProvider.fakeCaptchaResponse,
  387. recaptchaVersion: PhoneAuthProvider.recaptchaVersion,
  388. clientType: PhoneAuthProvider.clientType
  389. )
  390. }
  391. do {
  392. if let idToken = session.idToken {
  393. let request = StartMFAEnrollmentRequest(idToken: idToken,
  394. enrollmentInfo: startMFARequestInfo,
  395. requestConfiguration: auth.requestConfiguration)
  396. let response = try await auth.backend.call(with: request)
  397. return response.phoneSessionInfo?.sessionInfo
  398. } else {
  399. let request = StartMFASignInRequest(MFAPendingCredential: session.mfaPendingCredential,
  400. MFAEnrollmentID: session.multiFactorInfo?.uid,
  401. signInInfo: startMFARequestInfo,
  402. requestConfiguration: auth.requestConfiguration)
  403. let response = try await auth.backend.call(with: request)
  404. return response.responseInfo.sessionInfo
  405. }
  406. } catch {
  407. return try await handleVerifyErrorWithRetry(
  408. error: error,
  409. phoneNumber: phoneNumber,
  410. retryOnInvalidAppCredential: retryOnInvalidAppCredential,
  411. multiFactorSession: session,
  412. uiDelegate: uiDelegate,
  413. auditFallback: auditFallback
  414. )
  415. }
  416. }
  417. /// This method is only called when Audit failed on rCE on invalid-app-credential exception
  418. private func handleVerifyErrorWithRetry(error: Error,
  419. phoneNumber: String,
  420. retryOnInvalidAppCredential: Bool,
  421. multiFactorSession session: MultiFactorSession?,
  422. uiDelegate: AuthUIDelegate?,
  423. auditFallback: Bool = false) async throws -> String? {
  424. if (error as NSError).code == AuthErrorCode.invalidAppCredential.rawValue {
  425. if retryOnInvalidAppCredential {
  426. auth.appCredentialManager.clearCredential()
  427. return try await verifyClAndSendVerificationCode(toPhoneNumber: phoneNumber,
  428. retryOnInvalidAppCredential: false,
  429. multiFactorSession: session,
  430. uiDelegate: uiDelegate,
  431. auditFallback: auditFallback)
  432. }
  433. throw AuthErrorUtils.unexpectedResponse(deserializedResponse: nil, underlyingError: error)
  434. }
  435. throw error
  436. }
  437. /// Continues the flow to verify the client via silent push notification.
  438. private func verifyClient(withUIDelegate uiDelegate: AuthUIDelegate?) async throws
  439. -> CodeIdentity {
  440. // Remove the simulator check below after FCM supports APNs in simulators
  441. #if targetEnvironment(simulator)
  442. let environment = ProcessInfo().environment
  443. if environment["XCTestConfigurationFilePath"] == nil {
  444. return try await CodeIdentity
  445. .recaptcha(reCAPTCHAFlowWithUIDelegate(withUIDelegate: uiDelegate))
  446. }
  447. #endif
  448. if let credential = auth.appCredentialManager.credential {
  449. return CodeIdentity.credential(credential)
  450. }
  451. var token: AuthAPNSToken
  452. do {
  453. token = try await auth.tokenManager.getToken()
  454. } catch {
  455. return try await CodeIdentity
  456. .recaptcha(reCAPTCHAFlowWithUIDelegate(withUIDelegate: uiDelegate))
  457. }
  458. let request = VerifyClientRequest(withAppToken: token.string,
  459. isSandbox: token.type == AuthAPNSTokenType.sandbox,
  460. requestConfiguration: auth.requestConfiguration)
  461. do {
  462. let verifyResponse = try await auth.backend.call(with: request)
  463. guard let receipt = verifyResponse.receipt,
  464. let timeout = verifyResponse.suggestedTimeOutDate?.timeIntervalSinceNow else {
  465. fatalError("Internal Auth Error: invalid VerifyClientResponse")
  466. }
  467. let credential = await
  468. auth.appCredentialManager.didStartVerification(withReceipt: receipt, timeout: timeout)
  469. if credential.secret == nil {
  470. AuthLog.logWarning(code: "I-AUT000014", message: "Failed to receive remote " +
  471. "notification to verify app identity within \(timeout) " +
  472. "second(s), falling back to reCAPTCHA verification.")
  473. return try await CodeIdentity
  474. .recaptcha(reCAPTCHAFlowWithUIDelegate(withUIDelegate: uiDelegate))
  475. }
  476. return CodeIdentity.credential(credential)
  477. } catch {
  478. let nserror = error as NSError
  479. // reCAPTCHA Flow if it's an invalid app credential or a missing app token.
  480. guard nserror.code == AuthErrorCode.invalidAppCredential.rawValue || nserror
  481. .code == AuthErrorCode.missingAppToken.rawValue else {
  482. throw error
  483. }
  484. return try await CodeIdentity
  485. .recaptcha(reCAPTCHAFlowWithUIDelegate(withUIDelegate: uiDelegate))
  486. }
  487. }
  488. /// Continues the flow to verify the client via silent push notification.
  489. private func reCAPTCHAFlowWithUIDelegate(withUIDelegate uiDelegate: AuthUIDelegate?) async throws
  490. -> String {
  491. let eventID = AuthWebUtils.randomString(withLength: 10)
  492. guard let url = try await reCAPTCHAURL(withEventID: eventID) else {
  493. fatalError(
  494. "Internal error: reCAPTCHAURL returned neither a value nor an error. Report issue"
  495. )
  496. }
  497. let callbackMatcher: (URL?) -> Bool = { callbackURL in
  498. AuthWebUtils.isExpectedCallbackURL(
  499. callbackURL,
  500. eventID: eventID,
  501. authType: self.kAuthTypeVerifyApp,
  502. callbackScheme: self.callbackScheme
  503. )
  504. }
  505. return try await withUnsafeThrowingContinuation { continuation in
  506. self.auth.authURLPresenter.present(url,
  507. uiDelegate: uiDelegate,
  508. callbackMatcher: callbackMatcher) { callbackURL, error in
  509. if let error {
  510. continuation.resume(throwing: error)
  511. } else {
  512. do {
  513. try continuation.resume(returning: self.reCAPTCHAToken(forURL: callbackURL))
  514. } catch {
  515. continuation.resume(throwing: error)
  516. }
  517. }
  518. }
  519. }
  520. }
  521. /// Parses the reCAPTCHA URL and returns the reCAPTCHA token.
  522. /// - Parameter url: The url to be parsed for a reCAPTCHA token.
  523. /// - Returns: The reCAPTCHA token if successful.
  524. private func reCAPTCHAToken(forURL url: URL?) throws -> String {
  525. guard let url = url else {
  526. let reason = "Internal Auth Error: nil URL trying to access RECAPTCHA token"
  527. throw AuthErrorUtils.appVerificationUserInteractionFailure(reason: reason)
  528. }
  529. let actualURLComponents = URLComponents(url: url, resolvingAgainstBaseURL: false)
  530. if let queryItems = actualURLComponents?.queryItems,
  531. let deepLinkURL = AuthWebUtils.queryItemValue(name: "deep_link_id", from: queryItems) {
  532. let deepLinkComponents = URLComponents(string: deepLinkURL)
  533. if let queryItems = deepLinkComponents?.queryItems {
  534. if let token = AuthWebUtils.queryItemValue(name: "recaptchaToken", from: queryItems) {
  535. return token
  536. }
  537. if let firebaseError = AuthWebUtils.queryItemValue(
  538. name: "firebaseError",
  539. from: queryItems
  540. ) {
  541. if let errorData = firebaseError.data(using: .utf8) {
  542. var errorDict: [AnyHashable: Any]?
  543. do {
  544. errorDict = try JSONSerialization.jsonObject(with: errorData) as? [AnyHashable: Any]
  545. } catch {
  546. throw AuthErrorUtils.JSONSerializationError(underlyingError: error)
  547. }
  548. if let errorDict,
  549. let code = errorDict["code"] as? String,
  550. let message = errorDict["message"] as? String {
  551. throw AuthErrorUtils.urlResponseError(code: code, message: message)
  552. }
  553. }
  554. }
  555. }
  556. let reason = "An unknown error occurred with the following response: \(deepLinkURL)"
  557. throw AuthErrorUtils.appVerificationUserInteractionFailure(reason: reason)
  558. }
  559. let reason = "Failed to get url Components for url: \(url)"
  560. throw AuthErrorUtils.appVerificationUserInteractionFailure(reason: reason)
  561. }
  562. /// Constructs a URL used for opening a reCAPTCHA app verification flow using a given event ID.
  563. /// - Parameter eventID: The event ID used for this purpose.
  564. private func reCAPTCHAURL(withEventID eventID: String) async throws -> URL? {
  565. let authDomain = try await AuthWebUtils
  566. .fetchAuthDomain(withRequestConfiguration: auth.requestConfiguration, backend: auth.backend)
  567. let bundleID = Bundle.main.bundleIdentifier
  568. let clientID = auth.app?.options.clientID
  569. let appID = auth.app?.options.googleAppID
  570. let apiKey = auth.requestConfiguration.apiKey
  571. let appCheck = auth.requestConfiguration.appCheck
  572. var queryItems = [URLQueryItem(name: "apiKey", value: apiKey),
  573. URLQueryItem(name: "authType", value: kAuthTypeVerifyApp),
  574. URLQueryItem(name: "ibi", value: bundleID ?? ""),
  575. URLQueryItem(name: "v", value: AuthBackend.authUserAgent()),
  576. URLQueryItem(name: "eventId", value: eventID)]
  577. if usingClientIDScheme {
  578. queryItems.append(URLQueryItem(name: "clientId", value: clientID))
  579. } else {
  580. queryItems.append(URLQueryItem(name: "appId", value: appID))
  581. }
  582. if let languageCode = auth.requestConfiguration.languageCode {
  583. queryItems.append(URLQueryItem(name: "hl", value: languageCode))
  584. }
  585. var components = URLComponents(string: "https://\(authDomain)/__/auth/handler?")
  586. components?.queryItems = queryItems
  587. if let appCheck {
  588. let tokenResult = await appCheck.getToken(forcingRefresh: false)
  589. if let error = tokenResult.error {
  590. AuthLog.logWarning(code: "I-AUT000018",
  591. message: "Error getting App Check token; using placeholder " +
  592. "token instead. Error: \(error)")
  593. }
  594. let appCheckTokenFragment = "fac=\(tokenResult.token)"
  595. components?.fragment = appCheckTokenFragment
  596. }
  597. return components?.url
  598. }
  599. private let auth: Auth
  600. private let callbackScheme: String
  601. private let usingClientIDScheme: Bool
  602. private var recaptchaVerifier: AuthRecaptchaVerifier?
  603. init(auth: Auth) {
  604. self.auth = auth
  605. if let clientID = auth.app?.options.clientID {
  606. let reverseClientIDScheme = clientID.components(separatedBy: ".").reversed()
  607. .joined(separator: ".")
  608. if AuthWebUtils.isCallbackSchemeRegistered(forCustomURLScheme: reverseClientIDScheme,
  609. urlTypes: auth.mainBundleUrlTypes) {
  610. callbackScheme = reverseClientIDScheme
  611. usingClientIDScheme = true
  612. return
  613. }
  614. }
  615. usingClientIDScheme = false
  616. if let appID = auth.app?.options.googleAppID {
  617. let dashedAppID = appID.replacingOccurrences(of: ":", with: "-")
  618. callbackScheme = "app-\(dashedAppID)"
  619. return
  620. }
  621. callbackScheme = ""
  622. recaptchaVerifier = AuthRecaptchaVerifier.shared(auth: auth)
  623. }
  624. private let kAuthTypeVerifyApp = "verifyApp"
  625. #endif
  626. }