Skip to content

Privacy-first password manager with built-in email aliasing. Fully encrypted and self-hostable.

Add Totp generator, indicator and model to iOS native logic (#1770)

Leendert de Borst81b19edd7f12
diff --git a/apps/mobile-app/ios/Autofill/Info.plist b/apps/mobile-app/ios/Autofill/Info.plist
index 138cd0a3a..a6d1331e1 100644
--- a/apps/mobile-app/ios/Autofill/Info.plist
+++ b/apps/mobile-app/ios/Autofill/Info.plist
@@ -33,6 +33,8 @@
<true/>
<key>ProvidesPasswords</key>
<true/>
+ <key>ProvidesOneTimeCodes</key>
+ <true/>
</dict>
</dict>
<key>NSExtensionPointIdentifier</key>
diff --git a/apps/mobile-app/ios/VaultModels/AutofillCredential.swift b/apps/mobile-app/ios/VaultModels/AutofillCredential.swift
index a75032874..f282f28cd 100644
--- a/apps/mobile-app/ios/VaultModels/AutofillCredential.swift
+++ b/apps/mobile-app/ios/VaultModels/AutofillCredential.swift
@@ -15,6 +15,7 @@ public struct AutofillCredential: Codable, Hashable, Equatable {
public let password: String?
public let notes: String?
public let passkey: Passkey?
+ public let totpSecret: String?
public let createdAt: Date
public let updatedAt: Date
@@ -29,6 +30,7 @@ public struct AutofillCredential: Codable, Hashable, Equatable {
password: String?,
notes: String?,
passkey: Passkey?,
+ totpSecret: String? = nil,
createdAt: Date,
updatedAt: Date
) {
@@ -42,6 +44,7 @@ public struct AutofillCredential: Codable, Hashable, Equatable {
self.password = password
self.notes = notes
self.passkey = passkey
+ self.totpSecret = totpSecret
self.createdAt = createdAt
self.updatedAt = updatedAt
}
@@ -50,7 +53,8 @@ public struct AutofillCredential: Codable, Hashable, Equatable {
/// - Parameters:
/// - item: The Item to convert from
/// - passkey: Optional passkey associated with this item
- public init(from item: Item, passkey: Passkey? = nil) {
+ /// - totpSecret: Optional TOTP secret key for this item
+ public init(from item: Item, passkey: Passkey? = nil, totpSecret: String? = nil) {
self.id = item.id
self.serviceName = item.name
self.serviceUrl = item.url
@@ -61,6 +65,7 @@ public struct AutofillCredential: Codable, Hashable, Equatable {
self.password = item.password
self.notes = item.getFieldValue(FieldKey.notesContent)
self.passkey = passkey
+ self.totpSecret = totpSecret
self.createdAt = item.createdAt
self.updatedAt = item.updatedAt
}
@@ -97,4 +102,10 @@ public struct AutofillCredential: Codable, Hashable, Equatable {
public var hasPasskey: Bool {
return passkey != nil
}
+
+ /// Returns true if this credential has a TOTP secret.
+ public var hasTotp: Bool {
+ guard let secret = totpSecret else { return false }
+ return !secret.isEmpty
+ }
}
diff --git a/apps/mobile-app/ios/VaultModels/TotpCode.swift b/apps/mobile-app/ios/VaultModels/TotpCode.swift
new file mode 100644
index 000000000..73b08aaf0
--- /dev/null
+++ b/apps/mobile-app/ios/VaultModels/TotpCode.swift
@@ -0,0 +1,42 @@
+import Foundation
+
+/// TotpCode type representing TOTP (Time-based One-Time Password) codes in the vault.
+public struct TotpCode: Codable, Hashable, Equatable {
+ public let id: UUID
+ public let name: String
+ public let secretKey: String
+ public let itemId: UUID
+ public let isDeleted: Bool
+
+ public init(
+ id: UUID,
+ name: String,
+ secretKey: String,
+ itemId: UUID,
+ isDeleted: Bool = false
+ ) {
+ self.id = id
+ self.name = name
+ self.secretKey = secretKey
+ self.itemId = itemId
+ self.isDeleted = isDeleted
+ }
+
+ public static func == (lhs: TotpCode, rhs: TotpCode) -> Bool {
+ return lhs.id == rhs.id
+ }
+
+ public func hash(into hasher: inout Hasher) {
+ hasher.combine(id)
+ }
+
+ // MARK: - Database Column Mapping
+
+ enum CodingKeys: String, CodingKey {
+ case id = "Id"
+ case name = "Name"
+ case secretKey = "SecretKey"
+ case itemId = "ItemId"
+ case isDeleted = "IsDeleted"
+ }
+}
diff --git a/apps/mobile-app/ios/VaultStoreKit/Database/Repositories/TotpRepository.swift b/apps/mobile-app/ios/VaultStoreKit/Database/Repositories/TotpRepository.swift
new file mode 100644
index 000000000..a3f3e5f84
--- /dev/null
+++ b/apps/mobile-app/ios/VaultStoreKit/Database/Repositories/TotpRepository.swift
@@ -0,0 +1,55 @@
+import Foundation
+import VaultModels
+
+/// Repository for managing TOTP codes in the vault database.
+public class TotpRepository: BaseRepository {
+ /// Get all TOTP codes for a specific item.
+ /// - Parameter itemId: The UUID of the item
+ /// - Returns: Array of TotpCode objects for the item
+ /// - Throws: Database errors
+ public func getTotpCodesForItem(_ itemId: UUID) throws -> [TotpCode] {
+ let query = """
+ SELECT Id, Name, SecretKey, ItemId, COALESCE(IsDeleted, 0) as IsDeleted
+ FROM TotpCodes
+ WHERE ItemId = ? AND IsDeleted = 0
+ ORDER BY Name ASC
+ """
+
+ let results = try client.executeQuery(query, params: [itemId.uuidString])
+ var totpCodes: [TotpCode] = []
+
+ for row in results {
+ guard let idString = row["Id"] as? String,
+ let id = UUID(uuidString: idString),
+ let name = row["Name"] as? String,
+ let secretKey = row["SecretKey"] as? String,
+ let itemIdString = row["ItemId"] as? String,
+ let itemIdParsed = UUID(uuidString: itemIdString) else {
+ continue
+ }
+
+ let isDeleted = (row["IsDeleted"] as? Int64 ?? 0) != 0
+
+ let totpCode = TotpCode(
+ id: id,
+ name: name,
+ secretKey: secretKey,
+ itemId: itemIdParsed,
+ isDeleted: isDeleted
+ )
+
+ totpCodes.append(totpCode)
+ }
+
+ return totpCodes
+ }
+
+ /// Get the first TOTP code for a specific item (convenience method).
+ /// - Parameter itemId: The UUID of the item
+ /// - Returns: Optional TotpCode if one exists
+ /// - Throws: Database errors
+ public func getFirstTotpCodeForItem(_ itemId: UUID) throws -> TotpCode? {
+ let codes = try getTotpCodesForItem(itemId)
+ return codes.first
+ }
+}
diff --git a/apps/mobile-app/ios/VaultStoreKit/VaultStore+DatabaseClient.swift b/apps/mobile-app/ios/VaultStoreKit/VaultStore+DatabaseClient.swift
index a1577f5f3..749a756ca 100644
--- a/apps/mobile-app/ios/VaultStoreKit/VaultStore+DatabaseClient.swift
+++ b/apps/mobile-app/ios/VaultStoreKit/VaultStore+DatabaseClient.swift
@@ -5,14 +5,17 @@ import SQLite
/// This allows VaultStore to be used with the repository pattern.
extension VaultStore: DatabaseClient {
/// The ItemRepository instance for this VaultStore.
- /// Lazily initialized to use self as the database client.
public var itemRepository: ItemRepository {
return ItemRepository(client: self)
}
/// The PasskeyRepository instance for this VaultStore.
- /// Lazily initialized to use self as the database client.
public var passkeyRepository: PasskeyRepository {
return PasskeyRepository(client: self)
}
+
+ /// The TotpRepository instance for this VaultStore.
+ public var totpRepository: TotpRepository {
+ return TotpRepository(client: self)
+ }
}
diff --git a/apps/mobile-app/ios/VaultStoreKit/VaultStore+Query.swift b/apps/mobile-app/ios/VaultStoreKit/VaultStore+Query.swift
index 4b3ec0774..b6b6a8aff 100644
--- a/apps/mobile-app/ios/VaultStoreKit/VaultStore+Query.swift
+++ b/apps/mobile-app/ios/VaultStoreKit/VaultStore+Query.swift
@@ -305,7 +305,11 @@ extension VaultStore {
let passkeys = try? getPasskeys(forItemId: item.id)
let passkey = passkeys?.first
- return AutofillCredential(from: item, passkey: passkey)
+ // Load TOTP secret for this item (gets first non-deleted TOTP code)
+ let totpCode = try? getFirstTotpCode(forItemId: item.id)
+ let totpSecret = totpCode?.secretKey
+
+ return AutofillCredential(from: item, passkey: passkey, totpSecret: totpSecret)
}
/// Get all items that have passkeys for passkey autofill.
@@ -319,4 +323,14 @@ extension VaultStore {
return credentials
}
+
+ // MARK: - TOTP Operations
+
+ /// Get the first TOTP code for a specific item.
+ /// - Parameter itemId: The UUID of the item
+ /// - Returns: Optional TotpCode if one exists
+ /// - Throws: Database errors
+ public func getFirstTotpCode(forItemId itemId: UUID) throws -> TotpCode? {
+ return try totpRepository.getFirstTotpCodeForItem(itemId)
+ }
}
diff --git a/apps/mobile-app/ios/VaultUI/Selection/Components/CredentialCardView.swift b/apps/mobile-app/ios/VaultUI/Selection/Components/CredentialCardView.swift
index cc78014a8..ee29172ec 100644
--- a/apps/mobile-app/ios/VaultUI/Selection/Components/CredentialCardView.swift
+++ b/apps/mobile-app/ios/VaultUI/Selection/Components/CredentialCardView.swift
@@ -31,9 +31,25 @@ public struct AutofillCredentialCard: View {
.frame(width: 32, height: 32)
VStack(alignment: .leading, spacing: 4) {
- Text(truncateText(credential.serviceName ?? "Unknown", limit: 26))
- .font(.headline)
- .foregroundColor(colors.text)
+ HStack(spacing: 4) {
+ Text(truncateText(credential.serviceName ?? "Unknown", limit: 26))
+ .font(.headline)
+ .foregroundColor(colors.text)
+
+ // Passkey indicator
+ if credential.hasPasskey {
+ Image(systemName: "person.badge.key")
+ .font(.system(size: 12))
+ .foregroundColor(colors.textMuted)
+ }
+
+ // TOTP indicator
+ if credential.hasTotp {
+ Image(systemName: "textformat.123")
+ .font(.system(size: 12))
+ .foregroundColor(colors.textMuted)
+ }
+ }
Text(truncateText(credential.identifier, limit: 26))
.font(.subheadline)
diff --git a/apps/mobile-app/ios/VaultUI/Selection/CredentialProviderView.swift b/apps/mobile-app/ios/VaultUI/Selection/CredentialProviderView.swift
index 894b2153e..5d2de9c15 100644
--- a/apps/mobile-app/ios/VaultUI/Selection/CredentialProviderView.swift
+++ b/apps/mobile-app/ios/VaultUI/Selection/CredentialProviderView.swift
@@ -1,6 +1,7 @@
import SwiftUI
import AuthenticationServices
import VaultModels
+import VaultUtils
private let locBundle = Bundle.vaultUI
@@ -163,11 +164,16 @@ private struct AutofillCredentialCardWithSelection: View {
let onCopy: () -> Void
@State private var showSelectionSheet = false
+ @State private var totpCode: String?
@Environment(\.colorScheme) private var colorScheme
var body: some View {
AutofillCredentialCard(credential: credential, action: {
if isChoosingTextToInsert {
+ // Generate TOTP code if available
+ if let secret = credential.totpSecret {
+ totpCode = TotpGenerator.generateCode(secret: secret)
+ }
showSelectionSheet = true
} else {
// For normal autofill, use the credential's identifier property
@@ -198,6 +204,12 @@ private struct AutofillCredentialCardWithSelection: View {
onSelect(credential.password ?? "", "")
}
+ if let code = totpCode, !code.isEmpty {
+ Button(String(localized: "totp_code", bundle: locBundle) + ": " + code) {
+ onSelect(code, "")
+ }
+ }
+
Button(String(localized: "cancel", bundle: locBundle), role: .cancel) {}
} message: {
Text(String(localized: "select_text_to_insert_message", bundle: locBundle))
diff --git a/apps/mobile-app/ios/VaultUI/en.lproj/Localizable.strings b/apps/mobile-app/ios/VaultUI/en.lproj/Localizable.strings
index 654050f84..50fc875e4 100644
--- a/apps/mobile-app/ios/VaultUI/en.lproj/Localizable.strings
+++ b/apps/mobile-app/ios/VaultUI/en.lproj/Localizable.strings
@@ -32,6 +32,7 @@
"username_copied" = "Username copied";
"password_copied" = "Password copied";
"email_copied" = "Email copied";
+"totp_code" = "TOTP Code";
/* Search bar */
"search_items" = "Search items...";
diff --git a/apps/mobile-app/ios/VaultUtils/TotpGenerator.swift b/apps/mobile-app/ios/VaultUtils/TotpGenerator.swift
new file mode 100644
index 000000000..405d322cd
--- /dev/null
+++ b/apps/mobile-app/ios/VaultUtils/TotpGenerator.swift
@@ -0,0 +1,137 @@
+import Foundation
+import CommonCrypto
+
+/// Utility class for generating Time-based One-Time Passwords (TOTP) codes.
+/// Implements RFC 6238 TOTP algorithm.
+public class TotpGenerator {
+ /// Generate a TOTP code from a secret key.
+ /// - Parameters:
+ /// - secret: The Base32-encoded secret key
+ /// - time: The current time (defaults to now)
+ /// - period: The time step in seconds (defaults to 30)
+ /// - digits: Number of digits in the code (defaults to 6)
+ /// - Returns: The generated TOTP code as a string, or nil if generation fails
+ public static func generateCode(
+ secret: String,
+ time: Date = Date(),
+ period: Int = 30,
+ digits: Int = 6
+ ) -> String? {
+ // Decode the Base32 secret
+ guard let secretData = base32Decode(secret) else {
+ return nil
+ }
+
+ // Calculate the time counter
+ let counter = UInt64(time.timeIntervalSince1970) / UInt64(period)
+
+ // Generate HOTP code
+ return generateHOTP(secret: secretData, counter: counter, digits: digits)
+ }
+
+ /// Generate an HMAC-based One-Time Password (HOTP) code.
+ /// - Parameters:
+ /// - secret: The secret key as Data
+ /// - counter: The counter value
+ /// - digits: Number of digits in the code
+ /// - Returns: The generated HOTP code as a string
+ private static func generateHOTP(secret: Data, counter: UInt64, digits: Int) -> String {
+ // Convert counter to 8-byte big-endian
+ var counterBytes = counter.bigEndian
+ let counterData = Data(bytes: &counterBytes, count: 8)
+
+ // Calculate HMAC-SHA1
+ var hmac = [UInt8](repeating: 0, count: Int(CC_SHA1_DIGEST_LENGTH))
+ secret.withUnsafeBytes { secretBytes in
+ counterData.withUnsafeBytes { counterBytes in
+ CCHmac(
+ CCHmacAlgorithm(kCCHmacAlgSHA1),
+ secretBytes.baseAddress,
+ secret.count,
+ counterBytes.baseAddress,
+ counterData.count,
+ &hmac
+ )
+ }
+ }
+
+ // Dynamic truncation
+ let offset = Int(hmac[hmac.count - 1] & 0x0F)
+ let truncatedHash = hmac[offset..<offset + 4]
+
+ // Convert to UInt32 and apply mask
+ var code: UInt32 = 0
+ for byte in truncatedHash {
+ code = (code << 8) | UInt32(byte)
+ }
+ code &= 0x7FFFFFFF
+
+ // Generate the final code with specified number of digits
+ let modulo = UInt32(pow(10.0, Double(digits)))
+ let otp = code % modulo
+
+ // Format with leading zeros
+ return String(format: "%0\(digits)d", otp)
+ }
+
+ /// Decode a Base32-encoded string.
+ /// - Parameter string: The Base32-encoded string
+ /// - Returns: The decoded Data, or nil if decoding fails
+ private static func base32Decode(_ string: String) -> Data? {
+ // Remove spaces and convert to uppercase
+ let cleanedString = string
+ .replacingOccurrences(of: " ", with: "")
+ .replacingOccurrences(of: "-", with: "")
+ .uppercased()
+
+ // Base32 alphabet (RFC 4648)
+ let base32Alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"
+
+ var bits = ""
+
+ // Convert each character to its 5-bit binary representation
+ for char in cleanedString {
+ guard let index = base32Alphabet.firstIndex(of: char) else {
+ // Invalid character in Base32 string
+ return nil
+ }
+ let value = base32Alphabet.distance(from: base32Alphabet.startIndex, to: index)
+ bits += String(value, radix: 2).padLeft(toLength: 5, withPad: "0")
+ }
+
+ // Convert binary string to bytes
+ var bytes = [UInt8]()
+ for iVal in stride(from: 0, to: bits.count, by: 8) {
+ let endIndex = min(iVal + 8, bits.count)
+ let byteBits = bits[bits.index(bits.startIndex, offsetBy: iVal)..<bits.index(bits.startIndex, offsetBy: endIndex)]
+ if byteBits.count == 8 {
+ if let byte = UInt8(byteBits, radix: 2) {
+ bytes.append(byte)
+ }
+ }
+ }
+
+ return Data(bytes)
+ }
+
+ /// Get the remaining seconds until the next TOTP code.
+ /// - Parameters:
+ /// - time: The current time (defaults to now)
+ /// - period: The time step in seconds (defaults to 30)
+ /// - Returns: The number of seconds remaining
+ public static func getRemainingSeconds(time: Date = Date(), period: Int = 30) -> Int {
+ let elapsed = Int(time.timeIntervalSince1970) % period
+ return period - elapsed
+ }
+}
+
+/// String extension for padding.
+private extension String {
+ func padLeft(toLength length: Int, withPad pad: String) -> String {
+ let padLength = length - self.count
+ if padLength <= 0 {
+ return self
+ }
+ return String(repeating: pad, count: padLength) + self
+ }
+}