PhoneAuthProvider.swift 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670
  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. if let settings = auth.settings,
  194. settings.isAppVerificationDisabledForTesting {
  195. // If app verification is disabled for testing
  196. // do not fetch recaptcha config, as this is not implemented in emulator
  197. // Treat this same as RCE enable status off
  198. return try await verifyClAndSendVerificationCode(
  199. toPhoneNumber: phoneNumber,
  200. retryOnInvalidAppCredential: true,
  201. multiFactorSession: multiFactorSession,
  202. uiDelegate: uiDelegate
  203. )
  204. }
  205. try await recaptchaVerifier.retrieveRecaptchaConfig(forceRefresh: true)
  206. switch recaptchaVerifier.enablementStatus(forProvider: .phone) {
  207. case .off:
  208. return try await verifyClAndSendVerificationCode(
  209. toPhoneNumber: phoneNumber,
  210. retryOnInvalidAppCredential: true,
  211. multiFactorSession: multiFactorSession,
  212. uiDelegate: uiDelegate
  213. )
  214. case .audit:
  215. return try await verifyClAndSendVerificationCodeWithRecaptcha(
  216. toPhoneNumber: phoneNumber,
  217. retryOnInvalidAppCredential: true,
  218. multiFactorSession: multiFactorSession,
  219. uiDelegate: uiDelegate,
  220. recaptchaVerifier: recaptchaVerifier
  221. )
  222. case .enforce:
  223. return try await verifyClAndSendVerificationCodeWithRecaptcha(
  224. toPhoneNumber: phoneNumber,
  225. retryOnInvalidAppCredential: false,
  226. multiFactorSession: multiFactorSession,
  227. uiDelegate: uiDelegate,
  228. recaptchaVerifier: recaptchaVerifier
  229. )
  230. }
  231. }
  232. func verifyClAndSendVerificationCodeWithRecaptcha(toPhoneNumber phoneNumber: String,
  233. retryOnInvalidAppCredential: Bool,
  234. uiDelegate: AuthUIDelegate?,
  235. recaptchaVerifier: AuthRecaptchaVerifier) async throws
  236. -> String? {
  237. let request = SendVerificationCodeRequest(phoneNumber: phoneNumber,
  238. codeIdentity: CodeIdentity.empty,
  239. requestConfiguration: auth
  240. .requestConfiguration)
  241. do {
  242. try await recaptchaVerifier.injectRecaptchaFields(
  243. request: request,
  244. provider: .phone,
  245. action: .sendVerificationCode
  246. )
  247. let response = try await auth.backend.call(with: request)
  248. return response.verificationID
  249. } catch {
  250. return try await handleVerifyErrorWithRetry(error: error,
  251. phoneNumber: phoneNumber,
  252. retryOnInvalidAppCredential: retryOnInvalidAppCredential,
  253. multiFactorSession: nil,
  254. uiDelegate: uiDelegate,
  255. auditFallback: true)
  256. }
  257. }
  258. /// Starts the flow to verify the client via silent push notification.
  259. /// - Parameter retryOnInvalidAppCredential: Whether or not the flow should be retried if an
  260. /// AuthErrorCodeInvalidAppCredential error is returned from the backend.
  261. /// - Parameter phoneNumber: The phone number to be verified.
  262. /// - Parameter callback: The callback to be invoked on the global work queue when the flow is
  263. /// finished.
  264. private func verifyClAndSendVerificationCode(toPhoneNumber phoneNumber: String,
  265. retryOnInvalidAppCredential: Bool,
  266. uiDelegate: AuthUIDelegate?,
  267. auditFallback: Bool = false) async throws
  268. -> String? {
  269. let codeIdentity = try await verifyClient(withUIDelegate: uiDelegate)
  270. let request = SendVerificationCodeRequest(phoneNumber: phoneNumber,
  271. codeIdentity: codeIdentity,
  272. requestConfiguration: auth
  273. .requestConfiguration)
  274. if auditFallback {
  275. request.injectRecaptchaFields(
  276. recaptchaResponse: PhoneAuthProvider.fakeCaptchaResponse,
  277. recaptchaVersion: PhoneAuthProvider.recaptchaVersion
  278. )
  279. }
  280. do {
  281. let response = try await auth.backend.call(with: request)
  282. return response.verificationID
  283. } catch {
  284. return try await handleVerifyErrorWithRetry(
  285. error: error,
  286. phoneNumber: phoneNumber,
  287. retryOnInvalidAppCredential: retryOnInvalidAppCredential,
  288. multiFactorSession: nil,
  289. uiDelegate: uiDelegate,
  290. auditFallback: auditFallback
  291. )
  292. }
  293. }
  294. /// Starts the flow to verify the client via silent push notification. This is used in both
  295. /// .Audit and .Enforce mode
  296. /// - Parameter retryOnInvalidAppCredential: Whether or not the flow should be retried if an
  297. /// AuthErrorCodeInvalidAppCredential error is returned from the backend.
  298. /// - Parameter phoneNumber: The phone number to be verified.
  299. private func verifyClAndSendVerificationCodeWithRecaptcha(toPhoneNumber phoneNumber: String,
  300. retryOnInvalidAppCredential: Bool,
  301. multiFactorSession session: MultiFactorSession?,
  302. uiDelegate: AuthUIDelegate?,
  303. recaptchaVerifier: AuthRecaptchaVerifier) async throws
  304. -> String? {
  305. if let settings = auth.settings,
  306. settings.isAppVerificationDisabledForTesting {
  307. let request = SendVerificationCodeRequest(
  308. phoneNumber: phoneNumber,
  309. codeIdentity: CodeIdentity.empty,
  310. requestConfiguration: auth.requestConfiguration
  311. )
  312. let response = try await auth.backend.call(with: request)
  313. return response.verificationID
  314. }
  315. guard let session else {
  316. return try await verifyClAndSendVerificationCodeWithRecaptcha(
  317. toPhoneNumber: phoneNumber,
  318. retryOnInvalidAppCredential: retryOnInvalidAppCredential,
  319. uiDelegate: uiDelegate,
  320. recaptchaVerifier: recaptchaVerifier
  321. )
  322. }
  323. let startMFARequestInfo = AuthProtoStartMFAPhoneRequestInfo(phoneNumber: phoneNumber,
  324. codeIdentity: CodeIdentity.empty)
  325. do {
  326. if let idToken = session.idToken {
  327. let request = StartMFAEnrollmentRequest(idToken: idToken,
  328. enrollmentInfo: startMFARequestInfo,
  329. requestConfiguration: auth.requestConfiguration)
  330. try await recaptchaVerifier.injectRecaptchaFields(
  331. request: request,
  332. provider: .phone,
  333. action: .mfaSmsEnrollment
  334. )
  335. let response = try await auth.backend.call(with: request)
  336. return response.phoneSessionInfo?.sessionInfo
  337. } else {
  338. let request = StartMFASignInRequest(MFAPendingCredential: session.mfaPendingCredential,
  339. MFAEnrollmentID: session.multiFactorInfo?.uid,
  340. signInInfo: startMFARequestInfo,
  341. requestConfiguration: auth.requestConfiguration)
  342. try await recaptchaVerifier.injectRecaptchaFields(
  343. request: request,
  344. provider: .phone,
  345. action: .mfaSmsSignIn
  346. )
  347. let response = try await auth.backend.call(with: request)
  348. return response.responseInfo.sessionInfo
  349. }
  350. } catch {
  351. // For Audit fallback only after rCE check failed
  352. return try await handleVerifyErrorWithRetry(
  353. error: error,
  354. phoneNumber: phoneNumber,
  355. retryOnInvalidAppCredential: retryOnInvalidAppCredential,
  356. multiFactorSession: session,
  357. uiDelegate: uiDelegate,
  358. auditFallback: true
  359. )
  360. }
  361. }
  362. /// Starts the flow to verify the client via silent push notification.
  363. /// This method is called in Audit fallback flow with "NO_RECAPTCHA" fake token and Off flow
  364. /// - Parameter retryOnInvalidAppCredential: Whether or not the flow should be retried if an
  365. /// AuthErrorCodeInvalidAppCredential error is returned from the backend.
  366. /// - Parameter phoneNumber: The phone number to be verified.
  367. private func verifyClAndSendVerificationCode(toPhoneNumber phoneNumber: String,
  368. retryOnInvalidAppCredential: Bool,
  369. multiFactorSession session: MultiFactorSession?,
  370. uiDelegate: AuthUIDelegate?,
  371. auditFallback: Bool = false) async throws
  372. -> String? {
  373. if let settings = auth.settings,
  374. settings.isAppVerificationDisabledForTesting {
  375. let request = SendVerificationCodeRequest(
  376. phoneNumber: phoneNumber,
  377. codeIdentity: CodeIdentity.empty,
  378. requestConfiguration: auth.requestConfiguration
  379. )
  380. let response = try await auth.backend.call(with: request)
  381. return response.verificationID
  382. }
  383. guard let session else {
  384. // Phone MFA flow
  385. return try await verifyClAndSendVerificationCode(
  386. toPhoneNumber: phoneNumber,
  387. retryOnInvalidAppCredential: retryOnInvalidAppCredential,
  388. uiDelegate: uiDelegate,
  389. auditFallback: auditFallback
  390. )
  391. }
  392. // MFA flows
  393. let codeIdentity = try await verifyClient(withUIDelegate: uiDelegate)
  394. let startMFARequestInfo = AuthProtoStartMFAPhoneRequestInfo(phoneNumber: phoneNumber,
  395. codeIdentity: codeIdentity)
  396. if auditFallback {
  397. startMFARequestInfo.injectRecaptchaFields(
  398. recaptchaResponse: PhoneAuthProvider.fakeCaptchaResponse,
  399. recaptchaVersion: PhoneAuthProvider.recaptchaVersion,
  400. clientType: PhoneAuthProvider.clientType
  401. )
  402. }
  403. do {
  404. if let idToken = session.idToken {
  405. let request = StartMFAEnrollmentRequest(idToken: idToken,
  406. enrollmentInfo: startMFARequestInfo,
  407. requestConfiguration: auth.requestConfiguration)
  408. let response = try await auth.backend.call(with: request)
  409. return response.phoneSessionInfo?.sessionInfo
  410. } else {
  411. let request = StartMFASignInRequest(MFAPendingCredential: session.mfaPendingCredential,
  412. MFAEnrollmentID: session.multiFactorInfo?.uid,
  413. signInInfo: startMFARequestInfo,
  414. requestConfiguration: auth.requestConfiguration)
  415. let response = try await auth.backend.call(with: request)
  416. return response.responseInfo.sessionInfo
  417. }
  418. } catch {
  419. return try await handleVerifyErrorWithRetry(
  420. error: error,
  421. phoneNumber: phoneNumber,
  422. retryOnInvalidAppCredential: retryOnInvalidAppCredential,
  423. multiFactorSession: session,
  424. uiDelegate: uiDelegate,
  425. auditFallback: auditFallback
  426. )
  427. }
  428. }
  429. /// This method is only called when Audit failed on rCE on invalid-app-credential exception
  430. private func handleVerifyErrorWithRetry(error: Error,
  431. phoneNumber: String,
  432. retryOnInvalidAppCredential: Bool,
  433. multiFactorSession session: MultiFactorSession?,
  434. uiDelegate: AuthUIDelegate?,
  435. auditFallback: Bool = false) async throws -> String? {
  436. if (error as NSError).code == AuthErrorCode.invalidAppCredential.rawValue {
  437. if retryOnInvalidAppCredential {
  438. auth.appCredentialManager.clearCredential()
  439. return try await verifyClAndSendVerificationCode(toPhoneNumber: phoneNumber,
  440. retryOnInvalidAppCredential: false,
  441. multiFactorSession: session,
  442. uiDelegate: uiDelegate,
  443. auditFallback: auditFallback)
  444. }
  445. throw AuthErrorUtils.unexpectedResponse(deserializedResponse: nil, underlyingError: error)
  446. }
  447. throw error
  448. }
  449. /// Continues the flow to verify the client via silent push notification.
  450. private func verifyClient(withUIDelegate uiDelegate: AuthUIDelegate?) async throws
  451. -> CodeIdentity {
  452. // Remove the simulator check below after FCM supports APNs in simulators
  453. #if targetEnvironment(simulator)
  454. let environment = ProcessInfo().environment
  455. if environment["XCTestConfigurationFilePath"] == nil {
  456. return try await CodeIdentity
  457. .recaptcha(reCAPTCHAFlowWithUIDelegate(withUIDelegate: uiDelegate))
  458. }
  459. #endif
  460. if let credential = auth.appCredentialManager.credential {
  461. return CodeIdentity.credential(credential)
  462. }
  463. var token: AuthAPNSToken
  464. do {
  465. token = try await auth.tokenManager.getToken()
  466. } catch {
  467. return try await CodeIdentity
  468. .recaptcha(reCAPTCHAFlowWithUIDelegate(withUIDelegate: uiDelegate))
  469. }
  470. let request = VerifyClientRequest(withAppToken: token.string,
  471. isSandbox: token.type == AuthAPNSTokenType.sandbox,
  472. requestConfiguration: auth.requestConfiguration)
  473. do {
  474. let verifyResponse = try await auth.backend.call(with: request)
  475. guard let receipt = verifyResponse.receipt,
  476. let timeout = verifyResponse.suggestedTimeOutDate?.timeIntervalSinceNow else {
  477. fatalError("Internal Auth Error: invalid VerifyClientResponse")
  478. }
  479. let credential = await
  480. auth.appCredentialManager.didStartVerification(withReceipt: receipt, timeout: timeout)
  481. if credential.secret == nil {
  482. AuthLog.logWarning(code: "I-AUT000014", message: "Failed to receive remote " +
  483. "notification to verify app identity within \(timeout) " +
  484. "second(s), falling back to reCAPTCHA verification.")
  485. return try await CodeIdentity
  486. .recaptcha(reCAPTCHAFlowWithUIDelegate(withUIDelegate: uiDelegate))
  487. }
  488. return CodeIdentity.credential(credential)
  489. } catch {
  490. let nserror = error as NSError
  491. // reCAPTCHA Flow if it's an invalid app credential or a missing app token.
  492. guard nserror.code == AuthErrorCode.invalidAppCredential.rawValue || nserror
  493. .code == AuthErrorCode.missingAppToken.rawValue else {
  494. throw error
  495. }
  496. return try await CodeIdentity
  497. .recaptcha(reCAPTCHAFlowWithUIDelegate(withUIDelegate: uiDelegate))
  498. }
  499. }
  500. /// Continues the flow to verify the client via silent push notification.
  501. private func reCAPTCHAFlowWithUIDelegate(withUIDelegate uiDelegate: AuthUIDelegate?) async throws
  502. -> String {
  503. let eventID = AuthWebUtils.randomString(withLength: 10)
  504. guard let url = try await reCAPTCHAURL(withEventID: eventID) else {
  505. fatalError(
  506. "Internal error: reCAPTCHAURL returned neither a value nor an error. Report issue"
  507. )
  508. }
  509. let callbackMatcher: (URL?) -> Bool = { callbackURL in
  510. AuthWebUtils.isExpectedCallbackURL(
  511. callbackURL,
  512. eventID: eventID,
  513. authType: self.kAuthTypeVerifyApp,
  514. callbackScheme: self.callbackScheme
  515. )
  516. }
  517. return try await withUnsafeThrowingContinuation { continuation in
  518. self.auth.authURLPresenter.present(url,
  519. uiDelegate: uiDelegate,
  520. callbackMatcher: callbackMatcher) { callbackURL, error in
  521. if let error {
  522. continuation.resume(throwing: error)
  523. } else {
  524. do {
  525. try continuation.resume(returning: self.reCAPTCHAToken(forURL: callbackURL))
  526. } catch {
  527. continuation.resume(throwing: error)
  528. }
  529. }
  530. }
  531. }
  532. }
  533. /// Parses the reCAPTCHA URL and returns the reCAPTCHA token.
  534. /// - Parameter url: The url to be parsed for a reCAPTCHA token.
  535. /// - Returns: The reCAPTCHA token if successful.
  536. private func reCAPTCHAToken(forURL url: URL?) throws -> String {
  537. guard let url = url else {
  538. let reason = "Internal Auth Error: nil URL trying to access RECAPTCHA token"
  539. throw AuthErrorUtils.appVerificationUserInteractionFailure(reason: reason)
  540. }
  541. let actualURLComponents = URLComponents(url: url, resolvingAgainstBaseURL: false)
  542. if let queryItems = actualURLComponents?.queryItems,
  543. let deepLinkURL = AuthWebUtils.queryItemValue(name: "deep_link_id", from: queryItems) {
  544. let deepLinkComponents = URLComponents(string: deepLinkURL)
  545. if let queryItems = deepLinkComponents?.queryItems {
  546. if let token = AuthWebUtils.queryItemValue(name: "recaptchaToken", from: queryItems) {
  547. return token
  548. }
  549. if let firebaseError = AuthWebUtils.queryItemValue(
  550. name: "firebaseError",
  551. from: queryItems
  552. ) {
  553. if let errorData = firebaseError.data(using: .utf8) {
  554. var errorDict: [AnyHashable: Any]?
  555. do {
  556. errorDict = try JSONSerialization.jsonObject(with: errorData) as? [AnyHashable: Any]
  557. } catch {
  558. throw AuthErrorUtils.JSONSerializationError(underlyingError: error)
  559. }
  560. if let errorDict,
  561. let code = errorDict["code"] as? String,
  562. let message = errorDict["message"] as? String {
  563. throw AuthErrorUtils.urlResponseError(code: code, message: message)
  564. }
  565. }
  566. }
  567. }
  568. let reason = "An unknown error occurred with the following response: \(deepLinkURL)"
  569. throw AuthErrorUtils.appVerificationUserInteractionFailure(reason: reason)
  570. }
  571. let reason = "Failed to get url Components for url: \(url)"
  572. throw AuthErrorUtils.appVerificationUserInteractionFailure(reason: reason)
  573. }
  574. /// Constructs a URL used for opening a reCAPTCHA app verification flow using a given event ID.
  575. /// - Parameter eventID: The event ID used for this purpose.
  576. private func reCAPTCHAURL(withEventID eventID: String) async throws -> URL? {
  577. let authDomain = try await AuthWebUtils
  578. .fetchAuthDomain(withRequestConfiguration: auth.requestConfiguration, backend: auth.backend)
  579. let bundleID = Bundle.main.bundleIdentifier
  580. let clientID = auth.app?.options.clientID
  581. let appID = auth.app?.options.googleAppID
  582. let apiKey = auth.requestConfiguration.apiKey
  583. let appCheck = auth.requestConfiguration.appCheck
  584. var queryItems = [URLQueryItem(name: "apiKey", value: apiKey),
  585. URLQueryItem(name: "authType", value: kAuthTypeVerifyApp),
  586. URLQueryItem(name: "ibi", value: bundleID ?? ""),
  587. URLQueryItem(name: "v", value: AuthBackend.authUserAgent()),
  588. URLQueryItem(name: "eventId", value: eventID)]
  589. if usingClientIDScheme {
  590. queryItems.append(URLQueryItem(name: "clientId", value: clientID))
  591. } else {
  592. queryItems.append(URLQueryItem(name: "appId", value: appID))
  593. }
  594. if let languageCode = auth.requestConfiguration.languageCode {
  595. queryItems.append(URLQueryItem(name: "hl", value: languageCode))
  596. }
  597. var components = URLComponents(string: "https://\(authDomain)/__/auth/handler?")
  598. components?.queryItems = queryItems
  599. if let appCheck {
  600. let tokenResult = await appCheck.getToken(forcingRefresh: false)
  601. if let error = tokenResult.error {
  602. AuthLog.logWarning(code: "I-AUT000018",
  603. message: "Error getting App Check token; using placeholder " +
  604. "token instead. Error: \(error)")
  605. }
  606. let appCheckTokenFragment = "fac=\(tokenResult.token)"
  607. components?.fragment = appCheckTokenFragment
  608. }
  609. return components?.url
  610. }
  611. private let auth: Auth
  612. private let callbackScheme: String
  613. private let usingClientIDScheme: Bool
  614. private var recaptchaVerifier: AuthRecaptchaVerifier?
  615. init(auth: Auth) {
  616. self.auth = auth
  617. if let clientID = auth.app?.options.clientID {
  618. let reverseClientIDScheme = clientID.components(separatedBy: ".").reversed()
  619. .joined(separator: ".")
  620. if AuthWebUtils.isCallbackSchemeRegistered(forCustomURLScheme: reverseClientIDScheme,
  621. urlTypes: auth.mainBundleUrlTypes) {
  622. callbackScheme = reverseClientIDScheme
  623. usingClientIDScheme = true
  624. return
  625. }
  626. }
  627. usingClientIDScheme = false
  628. if let appID = auth.app?.options.googleAppID {
  629. let dashedAppID = appID.replacingOccurrences(of: ":", with: "-")
  630. callbackScheme = "app-\(dashedAppID)"
  631. return
  632. }
  633. callbackScheme = ""
  634. recaptchaVerifier = AuthRecaptchaVerifier.shared(auth: auth)
  635. }
  636. private let kAuthTypeVerifyApp = "verifyApp"
  637. #endif
  638. }