Privacy-first password manager with built-in email aliasing. Fully encrypted and self-hostable.
Update all TOTP calls to use new Rust core bindings (#2492)
Leendert de Borste330a6145bf0
diff --git a/apps/browser-extension/src/entrypoints/background/VaultMessageHandler.ts b/apps/browser-extension/src/entrypoints/background/VaultMessageHandler.tsindex e4f42f04a..fdd981203 100644--- a/apps/browser-extension/src/entrypoints/background/VaultMessageHandler.ts+++ b/apps/browser-extension/src/entrypoints/background/VaultMessageHandler.ts@@ -1309,7 +1309,7 @@ export async function handleGetTotpCodes(for (const item of message.items) {const totpCode = sqliteClient.items.getTotpCodesForItem(item)[0];- const code = totpCode ? generateTotpCode(totpCode.SecretKey, totpCode) : null;+ const code = totpCode ? await generateTotpCode(totpCode.SecretKey, totpCode) : null;if (code) {codes[scopedKey(item.ManifestId, item.Id)] = { Code: code, Period: normalizeTotpPeriod(totpCode.Period) };}@@ -1347,7 +1347,7 @@ export async function handleGenerateTotpCode(return { success: false, error: 'No TOTP codes found for this item' };}- const code = generateTotpCode(totpCodes[0].SecretKey, totpCodes[0]);+ const code = await generateTotpCode(totpCodes[0].SecretKey, totpCodes[0]);if (!code) {return { success: false, error: formatErrorWithCode(await t('common.errors.unknownError'), AppErrorCode.ITEM_READ_FAILED) };}diff --git a/apps/browser-extension/src/entrypoints/popup/components/Items/Details/TotpBlock.tsx b/apps/browser-extension/src/entrypoints/popup/components/Items/Details/TotpBlock.tsxindex 95a733454..48e4dc3ab 100644--- a/apps/browser-extension/src/entrypoints/popup/components/Items/Details/TotpBlock.tsx+++ b/apps/browser-extension/src/entrypoints/popup/components/Items/Details/TotpBlock.tsx@@ -90,32 +90,24 @@ const TotpBlock: React.FC<TotpBlockProps> = ({ itemId, manifestId }) => {}, [itemId, manifestId, dbContext?.sqliteClient]);useEffect(() => {+ let cancelled = false;+/**- * Updates the current TOTP codes.+ * Regenerates the codes; a failed code keeps its previous value so a single bad tick does not empty the displayed value.*/- const updateTotpCodes = (prevCodes: Record<string, string>): Record<string, string> => {- const newCodes: Record<string, string> = {};- totpCodes.forEach(code => {- // Keep the previous code when generation fails, so a single bad tick doesn't blank the display.- newCodes[code.Id] = generateTotpCode(code.SecretKey, code) ?? prevCodes[code.Id] ?? 'Error';- });- return newCodes;+ const refreshCodes = async (): Promise<void> => {+ const generated = await Promise.all(totpCodes.map(async code => [code.Id, await generateTotpCode(code.SecretKey, code)] as const));+ if (cancelled) {+ return;+ }+ setCurrentCodes(prevCodes => Object.fromEntries(generated.map(([id, code]) => [id, code ?? prevCodes[id] ?? 'Error'])));};- // Generate initial codes- const initialCodes: Record<string, string> = {};- totpCodes.forEach(code => {- initialCodes[code.Id] = generateTotpCode(code.SecretKey, code) ?? 'Error';- });- setCurrentCodes(initialCodes);-- // Set up interval to refresh codes- const intervalId = setInterval(() => {- setCurrentCodes(updateTotpCodes);- }, 1000);+ void refreshCodes();+ const intervalId = setInterval(() => void refreshCodes(), 1000);- // Clean up interval on unmount or when totpCodes changereturn () : void => {+ cancelled = true;clearInterval(intervalId);};}, [totpCodes]);diff --git a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/nativevaultmanager/NativeVaultManager.kt b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/nativevaultmanager/NativeVaultManager.ktindex 6f76e2b6e..6a4bd2652 100644--- a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/nativevaultmanager/NativeVaultManager.kt+++ b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/nativevaultmanager/NativeVaultManager.kt@@ -995,28 +995,6 @@ class NativeVaultManager(reactContext: ReactApplicationContext) :}}- /**- * Generate a TOTP code from a Base32-encoded secret using the stored RFC 6238 parameters.- * Delegates to the shared Kotlin TotpGenerator so the JS layer can reuse- * the same RFC 6238 implementation as the autofill service. Returns null- * for invalid secrets.- */- @ReactMethod- override fun generateTotpCode(secret: String, algorithm: String, digits: Double, period: Double, promise: Promise) {- try {- val code = net.aliasvault.app.utils.TotpGenerator.generateCode(- secret = secret,- period = period.toInt(),- digits = digits.toInt(),- algorithm = algorithm,- )- promise.resolve(code)- } catch (e: Exception) {- Log.e(TAG, "Error generating TOTP code", e)- promise.reject("ERR_TOTP_GENERATE", "Failed to generate TOTP code: ${e.message}", e)- }- }-/*** Get the current fragment activity.* @return The fragment activitydiff --git a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/nativevaultmanager/RustCoreDispatcher.kt b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/nativevaultmanager/RustCoreDispatcher.ktindex bdbafc5bc..ffa363f3e 100644--- a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/nativevaultmanager/RustCoreDispatcher.kt+++ b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/nativevaultmanager/RustCoreDispatcher.kt@@ -17,6 +17,7 @@ import uniffi.aliasvault_core.generateIdentityEmailPrefiximport uniffi.aliasvault_core.generateIdentityUsernameimport uniffi.aliasvault_core.generatePasswordimport uniffi.aliasvault_core.generateRandomEmailPrefix+import uniffi.aliasvault_core.generateTotpCodeimport uniffi.aliasvault_core.getDicewareLanguagesimport uniffi.aliasvault_core.getIdentityAgeRangesimport uniffi.aliasvault_core.getIdentityLanguages@@ -67,6 +68,7 @@ object RustCoreDispatcher {JSONObject().put("url", target.url).put("source", target.source).toString()}"filterCredentialsJson" -> filterCredentialsJson(args.string(0))+ "generateTotpCode" -> generateTotpCode(args.string(0), args.long(1), args.string(2), args.uint(3), args.uint(4))?.let { json(it) } ?: "null""generatePassword" -> json(generatePassword(args.string(0)))"getDicewareLanguages" -> json(getDicewareLanguages())@@ -124,6 +126,8 @@ object RustCoreDispatcher {fun uint(index: Int): UInt = values.getInt(index).toUInt()+ fun long(index: Int): Long = values.getLong(index)+fun strings(index: Int): List<String> {val array = values.getJSONArray(index)return (0 until array.length()).map { array.getString(it) }diff --git a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/utils/TotpGenerator.kt b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/utils/TotpGenerator.ktindex bc7d60670..8fed8fdb6 100644--- a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/utils/TotpGenerator.kt+++ b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/utils/TotpGenerator.kt@@ -1,33 +1,18 @@package net.aliasvault.app.utils-import android.util.Log-import java.nio.ByteBuffer-import javax.crypto.Mac-import javax.crypto.spec.SecretKeySpec-import kotlin.experimental.and+import uniffi.aliasvault_core.generateTotpCode/**- * RFC 6238 TOTP generator.+ * Time-based One-Time Password (TOTP) codes, generated by the Rust core (`core/rust/src/totp`).*/object TotpGenerator {- private const val TAG = "TotpGenerator"private const val DEFAULT_PERIOD = 30private const val DEFAULT_DIGITS = 6private const val DEFAULT_ALGORITHM = "SHA1"/**- * Map a TOTP algorithm name to its JCA Mac name. An unrecognized name falls back to- * HmacSHA1, which is what RFC 6238 assumes.- */- private fun macName(algorithm: String): String = when (algorithm.uppercase()) {- "SHA256" -> "HmacSHA256"- "SHA512" -> "HmacSHA512"- else -> "HmacSHA1"- }-- /**- * Generate the current TOTP code for a Base32-encoded secret.- * Returns null when the secret is invalid or HMAC fails.+ * Generate the TOTP code for a Base32-encoded secret.+ * Returns null when the secret is unusable.*/fun generateCode(secret: String,@@ -35,71 +20,5 @@ object TotpGenerator {period: Int = DEFAULT_PERIOD,digits: Int = DEFAULT_DIGITS,algorithm: String = DEFAULT_ALGORITHM,- ): String? {- val secretBytes = base32Decode(secret) ?: return null- if (secretBytes.isEmpty()) return null-- // A zero or negative period would divide by zero; treat it as the standard step.- val step = if (period > 0) period else DEFAULT_PERIOD- val counter = timeSeconds / step- return generateHotp(secretBytes, counter, digits, algorithm)- }-- private fun generateHotp(secret: ByteArray, counter: Long, digits: Int, algorithm: String): String? {- return try {- val counterBytes = ByteBuffer.allocate(Long.SIZE_BYTES).putLong(counter).array()-- val mac = Mac.getInstance(macName(algorithm))- mac.init(SecretKeySpec(secret, macName(algorithm)))- val hash = mac.doFinal(counterBytes)-- // Dynamic truncation per RFC 4226- val offset = (hash[hash.size - 1] and 0x0F).toInt()- val binary = ((hash[offset].toInt() and 0x7F) shl 24) or- ((hash[offset + 1].toInt() and 0xFF) shl 16) or- ((hash[offset + 2].toInt() and 0xFF) shl 8) or- (hash[offset + 3].toInt() and 0xFF)-- val mod = pow10(digits)- val code = binary % mod- code.toString().padStart(digits, '0')- } catch (e: Exception) {- Log.w(TAG, "TOTP HMAC generation failed", e)- null- }- }-- private fun pow10(n: Int): Int {- var result = 1- repeat(n) { result *= 10 }- return result- }-- /**- * Decode a Base32 (RFC 4648) string to bytes. Tolerates lowercase, spaces,- * and trailing padding ('='). Returns null on invalid characters.- */- private fun base32Decode(input: String): ByteArray? {- val cleaned = input.uppercase().replace(" ", "").replace("=", "")- if (cleaned.isEmpty()) return ByteArray(0)-- val alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"- val output = ByteArray((cleaned.length * 5) / 8)- var buffer = 0- var bitsLeft = 0- var index = 0-- for (ch in cleaned) {- val value = alphabet.indexOf(ch)- if (value < 0) return null- buffer = (buffer shl 5) or value- bitsLeft += 5- if (bitsLeft >= 8) {- output[index++] = ((buffer shr (bitsLeft - 8)) and 0xFF).toByte()- bitsLeft -= 8- }- }-- return output.copyOfRange(0, index)- }+ ): String? = generateTotpCode(secret, timeSeconds, algorithm, digits.coerceAtLeast(0).toUInt(), period.coerceAtLeast(0).toUInt())}diff --git a/apps/mobile-app/components/items/ItemCard.tsx b/apps/mobile-app/components/items/ItemCard.tsxindex 1e51e9e91..91d6e2f36 100644--- a/apps/mobile-app/components/items/ItemCard.tsx+++ b/apps/mobile-app/components/items/ItemCard.tsx@@ -12,13 +12,13 @@ import { ItemIcon } from '@/components/items/ItemIcon';import { useDialog } from '@/context/DialogContext';import { useDb } from '@/context/DbContext';import { LocalPreferencesService } from '@/services/LocalPreferencesService';-import { generateTotpCode } from '@/utils/TotpUtility';import { useColors } from '@/hooks/useColorScheme';import { useNavigationDebounce } from '@/hooks/useNavigationDebounce';import { copyToClipboardWithExpiration } from '@/utils/ClipboardUtility';import type { DisplayItem } from '@/utils/DisplayItem';import { itemEditRoute, itemRoute } from '@/utils/ItemRoute';import type { ItemRef } from '@aliasvault/client/database/ItemRef';+import { generateTotpCode } from '@aliasvault/client/items/TotpUtility';import { getFieldValue, FieldKey } from '@aliasvault/models/vault';type ItemCardProps = {diff --git a/apps/mobile-app/components/items/details/TotpSection.tsx b/apps/mobile-app/components/items/details/TotpSection.tsxindex 7a87515c3..4ea9320b4 100644--- a/apps/mobile-app/components/items/details/TotpSection.tsx+++ b/apps/mobile-app/components/items/details/TotpSection.tsx@@ -1,11 +1,11 @@import React, { useState, useEffect } from 'react';-import { generateTotpCode } from '@/utils/TotpUtility';import { useTranslation } from 'react-i18next';import { View, StyleSheet, TouchableOpacity, Platform } from 'react-native';import Toast from 'react-native-toast-message';import { copyToClipboardWithExpiration } from '@/utils/ClipboardUtility';+import { generateTotpCode } from '@aliasvault/client/items/TotpUtility';import type { Item, TotpCode } from '@aliasvault/models/vault';import { useColors } from '@/hooks/useColorScheme';@@ -105,7 +105,7 @@ export const TotpSection: React.FC<TotpSectionProps> = ({ item }) : React.ReactNlet cancelled = false;/**- * Generate codes for all current TOTP entries via the native bridge and+ * Generate codes for all current TOTP entries via the Rust core and* push them into state. Falls back to "Error" only when no previous code* exists for that entry, so the display doesn't flicker when a single* tick fails.diff --git a/apps/mobile-app/ios/AliasVault.xcodeproj/project.pbxproj b/apps/mobile-app/ios/AliasVault.xcodeproj/project.pbxprojindex 3f0553261..1f1285faa 100644--- a/apps/mobile-app/ios/AliasVault.xcodeproj/project.pbxproj+++ b/apps/mobile-app/ios/AliasVault.xcodeproj/project.pbxproj@@ -7,6 +7,7 @@objects = {/* Begin PBXBuildFile section */+ A7D10C012F000000000F0004 /* RustCoreFramework.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 61BC8C49EE3C1989FFB6DB3B /* RustCoreFramework.framework */; };07A10A71081ED4937FFAA625 /* RustCoreFramework.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 61BC8C49EE3C1989FFB6DB3B /* RustCoreFramework.framework */; };1381C2F6D317F2404928BA59 /* libPods-VaultUI.a in Frameworks */ = {isa = PBXBuildFile; fileRef = C32D89DCBA51D7C8CDE51DD2 /* libPods-VaultUI.a */; };13B07FBF1A68108700A75B9A /* Images.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 13B07FB51A68108700A75B9A /* Images.xcassets */; };@@ -57,6 +58,13 @@/* End PBXBuildFile section *//* Begin PBXContainerItemProxy section */+ A7D10C012F000000000F0005 /* PBXContainerItemProxy */ = {+ isa = PBXContainerItemProxy;+ containerPortal = 83CBB9F71A601CBA00E9B192 /* Project object */;+ proxyType = 1;+ remoteGlobalIDString = 55118F9387BE1BFE21365CB8;+ remoteInfo = RustCoreFramework;+ };1F09A0CB86D87B7C44135D75 /* PBXContainerItemProxy */ = {isa = PBXContainerItemProxy;containerPortal = 83CBB9F71A601CBA00E9B192 /* Project object */;@@ -360,6 +368,7 @@buildActionMask = 2147483647;files = (CE7782782EA3E70B00A75E6F /* VaultModels.framework in Frameworks */,+ A7D10C012F000000000F0004 /* RustCoreFramework.framework in Frameworks */,);runOnlyForDeploymentPostprocessing = 0;};@@ -743,6 +752,7 @@buildRules = ();dependencies = (+ A7D10C012F000000000F0006 /* PBXTargetDependency */,);fileSystemSynchronizedGroups = (CE77825E2EA1822400A75E6F /* VaultUtils */,@@ -1368,6 +1378,12 @@/* End PBXSourcesBuildPhase section *//* Begin PBXTargetDependency section */+ A7D10C012F000000000F0006 /* PBXTargetDependency */ = {+ isa = PBXTargetDependency;+ name = RustCoreFramework;+ target = 55118F9387BE1BFE21365CB8 /* RustCoreFramework */;+ targetProxy = A7D10C012F000000000F0005 /* PBXContainerItemProxy */;+ };174AAF666366E11F87CAB46E /* PBXTargetDependency */ = {isa = PBXTargetDependency;name = RustCoreFramework;diff --git a/apps/mobile-app/ios/NativeVaultManager/RCTNativeVaultManager.mm b/apps/mobile-app/ios/NativeVaultManager/RCTNativeVaultManager.mmindex caee9b454..6ca51165a 100644--- a/apps/mobile-app/ios/NativeVaultManager/RCTNativeVaultManager.mm+++ b/apps/mobile-app/ios/NativeVaultManager/RCTNativeVaultManager.mm@@ -179,10 +179,6 @@[vaultManager copyToClipboardWithExpiration:text expirationSeconds:expirationSeconds localOnly:localOnly resolver:resolve rejecter:reject];}-- (void)generateTotpCode:(NSString *)secret algorithm:(NSString *)algorithm digits:(double)digits period:(double)period resolve:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject {- [vaultManager generateTotpCode:secret algorithm:algorithm digits:digits period:period resolver:resolve rejecter:reject];-}-// MARK: - Android-specific methods (stubs for iOS)- (void)isIgnoringBatteryOptimizations:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject {diff --git a/apps/mobile-app/ios/NativeVaultManager/VaultManager.swift b/apps/mobile-app/ios/NativeVaultManager/VaultManager.swiftindex 94a9434ec..3f993e40b 100644--- a/apps/mobile-app/ios/NativeVaultManager/VaultManager.swift+++ b/apps/mobile-app/ios/NativeVaultManager/VaultManager.swift@@ -447,21 +447,6 @@ public class VaultManager: NSObject {resolve(nil)}- @objc- func generateTotpCode(_ secret: String,- algorithm: String,- digits: Double,- period: Double,- resolver resolve: @escaping RCTPromiseResolveBlock,- rejecter reject: @escaping RCTPromiseRejectBlock) {- // Returns nil for invalid secrets; the JS side treats null as "code unavailable".- let code = TotpGenerator.generateCode(secret: secret,- period: Int(period),- digits: Int(digits),- algorithm: algorithm)- resolve(code)- }-@objcfunc copyToClipboardWithExpiration(_ text: String,expirationSeconds: Double,@@ -1549,6 +1534,11 @@ private enum RustCoreDispatcher {return value.uint32Value}+ func int64(_ index: Int) throws -> Int64 {+ guard index < values.count, let value = values[index] as? NSNumber else { throw DispatchError.badArgument(index) }+ return value.int64Value+ }+func strings(_ index: Int) throws -> [String] {guard index < values.count, let value = values[index] as? [String] else { throw DispatchError.badArgument(index) }return value@@ -1579,6 +1569,9 @@ private enum RustCoreDispatcher {guard let target = RustCoreFramework.selectFaviconTarget(urls: try args.strings(0)) else { return "null" }return try json(["url": target.url, "source": target.source])case "filterCredentialsJson": return try RustCoreFramework.filterCredentialsJson(inputJson: try args.string(0))+ case "generateTotpCode":+ guard let code = RustCoreFramework.generateTotpCode(secret: try args.string(0), unixSeconds: try args.int64(1), algorithm: try args.string(2), digits: try args.uint32(3), period: try args.uint32(4)) else { return "null" }+ return try json(code)case "generatePassword": return try json(try RustCoreFramework.generatePassword(settingsJson: try args.string(0)))case "getDicewareLanguages": return try json(RustCoreFramework.getDicewareLanguages())diff --git a/apps/mobile-app/ios/VaultUtils/TotpGenerator.swift b/apps/mobile-app/ios/VaultUtils/TotpGenerator.swiftindex 1e757633b..37289a594 100644--- a/apps/mobile-app/ios/VaultUtils/TotpGenerator.swift+++ b/apps/mobile-app/ios/VaultUtils/TotpGenerator.swift@@ -1,22 +1,8 @@import Foundation-import CommonCrypto+import RustCoreFramework-/// Utility class for generating Time-based One-Time Passwords (TOTP) codes.-/// Implements RFC 6238 TOTP algorithm.+/// Time-based One-Time Password (TOTP) codes, generated by the Rust core (`core/rust/src/totp`).public class TotpGenerator {- /// The HMAC algorithms supported by the generator, mapped to their CommonCrypto identity.- /// An unrecognized name falls back to SHA1, which is what RFC 6238 assumes.- private static func hmacAlgorithm(for name: String) -> (algorithm: CCHmacAlgorithm, digestLength: Int) {- switch name.uppercased() {- case "SHA256":- return (CCHmacAlgorithm(kCCHmacAlgSHA256), Int(CC_SHA256_DIGEST_LENGTH))- case "SHA512":- return (CCHmacAlgorithm(kCCHmacAlgSHA512), Int(CC_SHA512_DIGEST_LENGTH))- default:- return (CCHmacAlgorithm(kCCHmacAlgSHA1), Int(CC_SHA1_DIGEST_LENGTH))- }- }-/// Generate a TOTP code from a secret key./// - Parameters:/// - secret: The Base32-encoded secret key@@ -24,7 +10,7 @@ public class TotpGenerator {/// - period: The time step in seconds (defaults to 30)/// - digits: Number of digits in the code (defaults to 6)/// - algorithm: The HMAC algorithm name: SHA1, SHA256 or SHA512 (defaults to SHA1)- /// - Returns: The generated TOTP code as a string, or nil if generation fails+ /// - Returns: The generated TOTP code, or nil if the secret is unusablepublic static func generateCode(secret: String,time: Date = Date(),@@ -32,127 +18,23 @@ public class TotpGenerator {digits: Int = 6,algorithm: String = "SHA1") -> String? {- // Decode the Base32 secret- guard let secretData = base32Decode(secret) else {- return nil- }-- // A zero or negative period would divide by zero; treat it as the standard step.- let step = period > 0 ? period : 30-- // Calculate the time counter- let counter = UInt64(time.timeIntervalSince1970) / UInt64(step)-- // Generate HOTP code- return generateHOTP(secret: secretData, counter: counter, digits: digits, algorithm: algorithm)- }-- /// 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- /// - algorithm: The HMAC algorithm name: SHA1, SHA256 or SHA512- /// - Returns: The generated HOTP code as a string- private static func generateHOTP(secret: Data, counter: UInt64, digits: Int, algorithm: String) -> String {- // Convert counter to 8-byte big-endian- var counterBytes = counter.bigEndian- let counterData = Data(bytes: &counterBytes, count: 8)-- // Calculate the HMAC using the requested algorithm- let hmacSpec = hmacAlgorithm(for: algorithm)- var hmac = [UInt8](repeating: 0, count: hmacSpec.digestLength)- secret.withUnsafeBytes { secretBytes in- counterData.withUnsafeBytes { counterBytes in- CCHmac(- hmacSpec.algorithm,- 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)+ return RustCoreFramework.generateTotpCode(+ secret: secret,+ unixSeconds: Int64(time.timeIntervalSince1970),+ algorithm: algorithm,+ digits: UInt32(clamping: digits),+ period: UInt32(clamping: period)+ )}/// 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)+ /// - period: The time step in seconds (defaults to 30); outside 1 to 300 the Rust core uses 30, and so does this/// - Returns: The number of seconds remainingpublic static func getRemainingSeconds(time: Date = Date(), period: Int = 30) -> Int {- let step = period > 0 ? period : 30+ let step = (1...300).contains(period) ? period : 30let elapsed = Int(time.timeIntervalSince1970) % stepreturn step - 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- }-}diff --git a/apps/mobile-app/platform/NativeRustCore.ts b/apps/mobile-app/platform/NativeRustCore.tsindex 4a34682b6..c87390811 100644--- a/apps/mobile-app/platform/NativeRustCore.ts+++ b/apps/mobile-app/platform/NativeRustCore.ts@@ -43,6 +43,8 @@ export const nativeRustCore: IRustCore = {selectFaviconTarget: (urls) => call('selectFaviconTarget', urls),filterCredentials: (input) => call('filterCredentialsJson', JSON.stringify(input)),+ generateTotpCode: (secret, unixSeconds, algorithm, digits, period) => call('generateTotpCode', secret, unixSeconds, algorithm, digits, period),+generatePassword: (settingsJson) => call('generatePassword', settingsJson),getDicewareLanguages: () => call('getDicewareLanguages'),generateIdentity: (requestJson) => call('generateIdentity', requestJson),diff --git a/apps/mobile-app/specs/NativeVaultManager.ts b/apps/mobile-app/specs/NativeVaultManager.tsindex 448b1ad23..c1dfc0ea8 100644--- a/apps/mobile-app/specs/NativeVaultManager.ts+++ b/apps/mobile-app/specs/NativeVaultManager.ts@@ -89,9 +89,6 @@ export interface Spec extends TurboModule {// Clipboard managementcopyToClipboardWithExpiration(text: string, expirationSeconds: number, localOnly: boolean): Promise<void>;- // TOTP code generation via native layer.- generateTotpCode(secret: string, algorithm: string, digits: number, period: number): Promise<string | null>;-// Battery optimization management (Android only)isIgnoringBatteryOptimizations(): Promise<boolean>;requestIgnoreBatteryOptimizations(): Promise<string>;diff --git a/apps/mobile-app/utils/TotpUtility.ts b/apps/mobile-app/utils/TotpUtility.tsdeleted file mode 100644index 3e1430fcf..000000000--- a/apps/mobile-app/utils/TotpUtility.ts+++ /dev/null@@ -1,31 +0,0 @@-import { normalizeTotpAlgorithm, normalizeTotpDigits, normalizeTotpPeriod } from '@aliasvault/models/vault';--import type { TotpParameters } from '@aliasvault/client/items/TotpUtility';--import NativeVaultManager from '@/specs/NativeVaultManager';--/**- * Generates the current TOTP code for the given secret key.- *- * Delegates to the platform-native TOTP generator (Swift on iOS, Kotlin on- * Android) so the React Native layer, the iOS Autofill extension, and the- * Android Autofill service all share one RFC 6238 implementation.- *- * @param secretKey - Base32-encoded TOTP secret- * @param parameters - Stored algorithm/digits/period; each falls back to the RFC 6238 default when absent- * @returns The current TOTP code, or empty string on error- */-export async function generateTotpCode(secretKey: string, parameters?: TotpParameters): Promise<string> {- try {- const code = await NativeVaultManager.generateTotpCode(- secretKey,- normalizeTotpAlgorithm(parameters?.Algorithm),- normalizeTotpDigits(parameters?.Digits),- normalizeTotpPeriod(parameters?.Period)- );- return code ?? '';- } catch (error) {- console.error('Error generating TOTP code:', error);- return '';- }-}diff --git a/apps/web/src/components/totp/TotpViewer.tsx b/apps/web/src/components/totp/TotpViewer.tsxindex dff0b69c0..7ba9adf72 100644--- a/apps/web/src/components/totp/TotpViewer.tsx+++ b/apps/web/src/components/totp/TotpViewer.tsx@@ -15,11 +15,6 @@ type TotpViewerProps = {item: ItemRef;};-/**- * The current code of a TOTP entry, or empty when the secret is unusable.- */-const codeOf = (totpCode: TotpCode): string => generateTotpCode(totpCode.SecretKey, totpCode) ?? '';-/*** A code split in two halves for readability ("123 456"); an odd length is shown as-is.*/@@ -31,11 +26,25 @@ const formatCode = (code: string): string => (code.length % 2 === 0 ? `${code.slconst TotpRow: React.FC<{ totpCode: TotpCode; item: ItemRef; tick: number }> = ({ totpCode, item, tick }) => {const { t } = useTranslation();const { copied, copyToClipboard } = useClipboardCopy(totpCode.Id, item);- const code = codeOf(totpCode);+ const [code, setCode] = useState('');const period = normalizeTotpPeriod(totpCode.Period);const remaining = getTotpRemainingSeconds(totpCode);const percentage = Math.floor(((period - remaining) / period) * 100);void tick;+ const timeStep = Math.floor(Date.now() / 1000 / period);++ // Generate a new code whenever the time step rolls over; an unusable secret shows as empty.+ useEffect(() => {+ let cancelled = false;+ void generateTotpCode(totpCode.SecretKey, totpCode).then(next => {+ if (!cancelled) {+ setCode(next ?? '');+ }+ });+ return (): void => {+ cancelled = true;+ };+ }, [totpCode, timeStep]);return (<button type="button" onClick={() => void copyToClipboard(code)} className="group w-full text-left p-2 ps-3 pe-3 bg-gray-50 border border-gray-200 rounded-lg cursor-pointer hover:bg-gray-100 transition-colors dark:bg-gray-700 dark:border-gray-600 dark:hover:bg-gray-600">diff --git a/core/client/package-lock.json b/core/client/package-lock.jsonindex 005166a58..af0618954 100644--- a/core/client/package-lock.json+++ b/core/client/package-lock.json@@ -13,8 +13,7 @@"@aliasvault/models": "file:../models","@aliasvault/vault": "file:../vault","dompurify": "^3.4.12",- "fflate": "^0.8.3",- "otpauth": "^9.3.6"+ "fflate": "^0.8.3"},"devDependencies": {"@types/node": "^22.13.10",@@ -468,18 +467,6 @@"@emnapi/runtime": "^1.7.1 || ^2.0.0-alpha.4"}},- "node_modules/@noble/hashes": {- "version": "2.4.0",- "resolved": "https://registry.npmjs.org/@noble/hashes/-/hashes-2.4.0.tgz",- "integrity": "sha512-X5XaVWZIBCT7HHZGm5I7ZQXDwLG+bGXuSrMQAW+7Zvl87h1kmc1ZB1VSRJcpUfoUrGQp4Fkoxm5kZ+Ms+aW+eA==",- "license": "MIT",- "engines": {- "node": ">= 20.19.0"- },- "funding": {- "url": "https://paulmillr.com/funding/"- }- },"node_modules/@oxc-project/types": {"version": "0.150.0","resolved": "https://registry.npmjs.org/@oxc-project/types/-/types-0.150.0.tgz",@@ -4229,18 +4216,6 @@"node": ">= 0.8.0"}},- "node_modules/otpauth": {- "version": "9.5.2",- "resolved": "https://registry.npmjs.org/otpauth/-/otpauth-9.5.2.tgz",- "integrity": "sha512-GQ5emWR/x1tcExT62IBT0UfO95wZzJZyxYOJOGVeQF47SYEN9vmh0vISvDZaNMuFJRG+IaWCKtfm+t9Bfoal6w==",- "license": "MIT",- "dependencies": {- "@noble/hashes": "2.4.0"- },- "funding": {- "url": "https://github.com/hectorm/otpauth?sponsor=1"- }- },"node_modules/own-keys": {"version": "1.0.2","resolved": "https://registry.npmjs.org/own-keys/-/own-keys-1.0.2.tgz",diff --git a/core/client/package.json b/core/client/package.jsonindex 595e76ebd..933fb857e 100644--- a/core/client/package.json+++ b/core/client/package.json@@ -24,8 +24,7 @@"@aliasvault/models": "file:../models","@aliasvault/vault": "file:../vault","dompurify": "^3.4.12",- "fflate": "^0.8.3",- "otpauth": "^9.3.6"+ "fflate": "^0.8.3"},"devDependencies": {"@types/node": "^22.13.10",diff --git a/core/client/src/items/TotpUtility.ts b/core/client/src/items/TotpUtility.tsindex 6fa391b86..eb9829609 100644--- a/core/client/src/items/TotpUtility.ts+++ b/core/client/src/items/TotpUtility.ts@@ -1,6 +1,6 @@import { normalizeTotpAlgorithm, normalizeTotpDigits, normalizeTotpPeriod } from '@aliasvault/models/vault';-import * as OTPAuth from 'otpauth';+import { rustCore } from '../rust/RustCore';import { logExpected } from '../utilities/Diagnostics';/**@@ -16,34 +16,18 @@ export type TotpParameters = {};/**- * Build an OTPAuth.TOTP for a secret using the stored parameters, falling back to the RFC 6238- * defaults for anything missing or unsupported.+ * Generate the TOTP code for a secret using its stored parameters, via the Rust core.** @param secretKey - Base32-encoded TOTP secret- * @param parameters - Stored algorithm/digits/period- * @returns A configured OTPAuth.TOTP instance+ * @param parameters - Stored algorithm/digits/period (when not set, use sha-1 common defaults instead)+ * @param unixSeconds - The moment to generate the code for, defaults to now+ * @returns The code, or null when the secret cannot be used*/-function createTotp(secretKey: string, parameters?: TotpParameters): OTPAuth.TOTP {- return new OTPAuth.TOTP({- secret: secretKey,- algorithm: normalizeTotpAlgorithm(parameters?.Algorithm),- digits: normalizeTotpDigits(parameters?.Digits),- period: normalizeTotpPeriod(parameters?.Period)- });-}--/**- * Generate the current TOTP code for a secret using its stored parameters.- *- * @param secretKey - Base32-encoded TOTP secret- * @param parameters - Stored algorithm/digits/period- * @returns The current code, or null when the secret cannot be used- */-export function generateTotpCode(secretKey: string, parameters?: TotpParameters): string | null {+export async function generateTotpCode(secretKey: string, parameters?: TotpParameters, unixSeconds: number = Math.floor(Date.now() / 1000)): Promise<string | null> {try {- return createTotp(secretKey, parameters).generate();+ return await rustCore().generateTotpCode(secretKey, unixSeconds, normalizeTotpAlgorithm(parameters?.Algorithm), normalizeTotpDigits(parameters?.Digits), normalizeTotpPeriod(parameters?.Period));} catch (error) {- logExpected('[Totp] The stored secret cannot generate a code', error);+ logExpected('[Totp] Generating a code failed', error);return null;}}diff --git a/core/client/src/rust/RustCoreBinding.ts b/core/client/src/rust/RustCoreBinding.tsindex 29acc1928..a215418b5 100644--- a/core/client/src/rust/RustCoreBinding.ts+++ b/core/client/src/rust/RustCoreBinding.ts@@ -30,6 +30,8 @@ export interface IRustCore {selectFaviconTarget(urls: string[]): Promise<FaviconTarget | null>;filterCredentials(input: FilterCredentialsInput): Promise<FilterCredentialsOutput>;+ generateTotpCode(secret: string, unixSeconds: number, algorithm: string, digits: number, period: number): Promise<string | null>;+generatePassword(settingsJson: string): Promise<string>;getDicewareLanguages(): Promise<string[]>;generateIdentity(requestJson: string): Promise<string>;diff --git a/core/client/src/rust/WasmRustCore.ts b/core/client/src/rust/WasmRustCore.tsindex 5a63d395c..84b02a82c 100644--- a/core/client/src/rust/WasmRustCore.ts+++ b/core/client/src/rust/WasmRustCore.ts@@ -54,6 +54,8 @@ export function createWasmRustCore(loadWasm: WasmLoader): IRustCore {selectFaviconTarget: (urls): Promise<FaviconTarget | null> => ready(() => (core.selectFaviconTarget(urls) ?? null) as FaviconTarget | null),filterCredentials: (input: FilterCredentialsInput): Promise<FilterCredentialsOutput> => ready(() => core.filterCredentials(input) as FilterCredentialsOutput),+ generateTotpCode: (secret, unixSeconds, algorithm, digits, period): Promise<string | null> => ready(() => core.generateTotpCode(secret, unixSeconds, algorithm, digits, period) ?? null),+generatePassword: (settingsJson): Promise<string> => ready(() => core.generatePassword(settingsJson)),getDicewareLanguages: (): Promise<string[]> => ready(() => core.getDicewareLanguages()),generateIdentity: (requestJson): Promise<string> => ready(() => core.generateIdentity(requestJson)),diff --git a/core/client/src/transfer/import/writers/TotpHelper.ts b/core/client/src/transfer/import/writers/TotpHelper.tsindex db21d939c..ec2fc17db 100644--- a/core/client/src/transfer/import/writers/TotpHelper.ts+++ b/core/client/src/transfer/import/writers/TotpHelper.ts@@ -1,25 +1,15 @@-import * as OTPAuth from 'otpauth';-import { isOtpAuthUri, resolveTotpEntry, type TotpEntry } from '../../../items/OtpAuthUri';/*** Sanitize an imported TOTP secret that may be given as an otpauth:// URI.* @param secretKey - The bare Base32 secret or an otpauth://totp/ URI* @returns The secret, name (derived from the URI's label and issuer, else blank) and parameters- * @throws {Error} When the URI is malformed or the secret cannot generate a code.+ * @throws {Error} When the URI is malformed or the secret is not Base32.*/export function sanitizeTotpSecretKey(secretKey: string): TotpEntry {const entry = resolveTotpEntry(secretKey, '');if (!entry) {throw new Error(isOtpAuthUri(secretKey) ? 'Invalid TOTP URI format. Please check and try again.' : 'Invalid secret key. Please check and try again.');}-- // The secret must be valid, check by trying to generate a code.- try {- new OTPAuth.TOTP({ secret: OTPAuth.Secret.fromBase32(entry.secretKey), algorithm: entry.algorithm, digits: entry.digits, period: entry.period }).generate();- } catch {- throw new Error('Invalid secret key. Please check and try again.');- }-return entry;}