TOTPSecret.swift 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123
  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 Foundation
  15. #if COCOAPODS
  16. internal import GoogleUtilities
  17. #else
  18. internal import GoogleUtilities_Environment
  19. #endif
  20. #if os(iOS) || os(macOS)
  21. #if os(iOS)
  22. import UIKit
  23. #elseif os(macOS)
  24. import AppKit
  25. #endif
  26. /// The subclass of base class MultiFactorAssertion, used to assert ownership of a TOTP
  27. /// (Time-based One Time Password) second factor.
  28. ///
  29. /// This class is available on iOS and macOS.
  30. @objc(FIRTOTPSecret) open class TOTPSecret: NSObject {
  31. /// Returns the shared secret key/seed used to generate time-based one-time passwords.
  32. @objc open func sharedSecretKey() -> String {
  33. return secretKey
  34. }
  35. /// Returns a QRCode URL as described in
  36. /// https://github.com/google/google-authenticator/wiki/Key-Uri-Format.
  37. ///
  38. /// This can be displayed to the user as a QRCode to be scanned into a TOTP app like Google
  39. /// Authenticator.
  40. /// - Parameter accountName: The name of the account/app.
  41. /// - Parameter issuer: Issuer of the TOTP(likely the app name).
  42. /// - Returns: A QRCode URL string.
  43. @objc(generateQRCodeURLWithAccountName:issuer:)
  44. open func generateQRCodeURL(withAccountName accountName: String,
  45. issuer: String) -> String {
  46. guard let hashingAlgorithm, codeLength > 0 else {
  47. return ""
  48. }
  49. return "otpauth://totp/\(issuer):\(accountName)?secret=\(secretKey)&issuer=\(issuer)" +
  50. "&algorithm=\(hashingAlgorithm)&digits=\(codeLength)"
  51. }
  52. /// Opens the specified QR Code URL in a password manager like iCloud Keychain.
  53. ///
  54. /// See more details
  55. /// [here](https://developer.apple.com/documentation/authenticationservices/securing_logins_with_icloud_keychain_verification_codes)
  56. @MainActor @objc(openInOTPAppWithQRCodeURL:)
  57. open func openInOTPApp(withQRCodeURL qrCodeURL: String) {
  58. if GULAppEnvironmentUtil.isAppExtension() {
  59. // App extensions should not call [UIApplication sharedApplication] or [NSWorkspace
  60. // sharedWorkspace], even if they respond to it.
  61. return
  62. }
  63. #if os(iOS)
  64. // Using reflection here to avoid build errors in extensions.
  65. let sel = NSSelectorFromString("sharedApplication")
  66. guard UIApplication.responds(to: sel),
  67. let rawApplication = UIApplication.perform(sel),
  68. let application = rawApplication.takeUnretainedValue() as? UIApplication else {
  69. return
  70. }
  71. if let url = URL(string: qrCodeURL), application.canOpenURL(url) {
  72. application.open(url, options: [:], completionHandler: nil)
  73. } else {
  74. AuthLog.logError(code: "I-AUT000019",
  75. message: "URL: \(qrCodeURL) cannot be opened")
  76. }
  77. #elseif os(macOS)
  78. if let url = URL(string: qrCodeURL) {
  79. NSWorkspace.shared.open(url)
  80. } else {
  81. AuthLog.logError(code: "I-AUT000019",
  82. message: "URL: \(qrCodeURL) cannot be opened")
  83. }
  84. #endif
  85. }
  86. /// Shared secret key/seed used for enrolling in TOTP MFA and generating OTPs.
  87. private let secretKey: String
  88. /// Hashing algorithm used.
  89. private let hashingAlgorithm: String?
  90. /// Length of the one-time passwords to be generated.
  91. private let codeLength: Int
  92. /// The interval (in seconds) when the OTP codes should change.
  93. private let codeIntervalSeconds: Int
  94. /// The timestamp by which TOTP enrollment should be completed. This can be used by callers to
  95. /// show a countdown of when to enter OTP code by.
  96. private let enrollmentCompletionDeadline: Date?
  97. /// Additional session information.
  98. let sessionInfo: String?
  99. init(secretKey: String, hashingAlgorithm: String?, codeLength: Int, codeIntervalSeconds: Int,
  100. enrollmentCompletionDeadline: Date?, sessionInfo: String?) {
  101. self.secretKey = secretKey
  102. self.hashingAlgorithm = hashingAlgorithm
  103. self.codeLength = codeLength
  104. self.codeIntervalSeconds = codeIntervalSeconds
  105. self.enrollmentCompletionDeadline = enrollmentCompletionDeadline
  106. self.sessionInfo = sessionInfo
  107. }
  108. }
  109. #endif