Skip to content

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

Add mobile app biometric/PIN authentication grace period

Leendert de Borste7acc127e899
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.kt
index 09e3f7613..371da2ea7 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
@@ -1600,9 +1600,21 @@ class NativeVaultManager(reactContext: ReactApplicationContext) :
}
@ReactMethod
- override fun authenticateUser(title: String?, subtitle: String?, allowedMethods: ReadableArray?, buttonText: String?, promise: Promise) {
+ override fun authenticateUser(
+ title: String?,
+ subtitle: String?,
+ allowedMethods: ReadableArray?,
+ buttonText: String?,
+ recentUnlockGraceSeconds: Double,
+ promise: Promise,
+ ) {
CoroutineScope(Dispatchers.Main).launch {
try {
+ if (vaultStore.wasRecentlyAuthenticated(recentUnlockGraceSeconds)) {
+ promise.resolve(true)
+ return@launch
+ }
+
// Get enabled authentication methods
val authMethods = vaultStore.getAuthMethods()
diff --git a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultAuth.kt b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultAuth.kt
index 14bcb2a20..588b1cb0c 100644
--- a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultAuth.kt
+++ b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultAuth.kt
@@ -11,6 +11,7 @@ import java.util.TimerTask
class VaultAuth(
private val storageProvider: StorageProvider,
private val onClearCache: () -> Unit,
+ private val onBackground: () -> Unit = {},
) {
companion object {
private const val TAG = "VaultAuth"
@@ -65,6 +66,10 @@ class VaultAuth(
val timeout = getAutoLockTimeout()
Log.d(TAG, "App entered background, starting auto-lock timer with ${timeout}s")
+ // Always drop the recency grace on backgrounding so it can't be honored on resume,
+ // independent of whether the auto-lock timer is scheduled (timeout == 0 disables it).
+ onBackground()
+
// Cancel any existing timer
clearCacheTimer?.cancel()
clearCacheTimer = null
diff --git a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultStore.kt b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultStore.kt
index 9659fb00d..5b06f65de 100644
--- a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultStore.kt
+++ b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultStore.kt
@@ -1,5 +1,6 @@
package net.aliasvault.app.vaultstore
+import android.os.SystemClock
import android.util.Log
import io.requery.android.database.sqlite.SQLiteDatabase
import kotlinx.coroutines.suspendCancellableCoroutine
@@ -47,6 +48,11 @@ class VaultStore(
*/
private const val BASE64_BLOB_PREFIX = "av-base64-to-blob:"
+ /**
+ * Hard cap on how long a recent-auth grace will be honored, regardless of caller input.
+ */
+ private const val MAX_AUTH_RECENCY_WINDOW_SECONDS: Double = 15.0
+
/**
* Get the instance of the vault store.
* @param keystoreProvider The keystore provider
@@ -73,13 +79,51 @@ class VaultStore(
}
}
+ // region Authentication Recency
+
+ /** Last successful biometric/PIN auth. */
+ @Volatile
+ private var lastSuccessfulAuthAtMs: Long? = null
+
+ /** Mark successful authorization call to be used for future recency checks. */
+ internal fun markSuccessfulAuth() {
+ lastSuccessfulAuthAtMs = SystemClock.elapsedRealtime()
+ }
+
+ /**
+ * Invalidate the recency timestamp. Must be called whenever the encryption key is cleared
+ * (lock, sign-out, auto-lock) so the grace window cannot outlive the unlocked state.
+ */
+ internal fun clearLastSuccessfulAuth() {
+ lastSuccessfulAuthAtMs = null
+ }
+
+ /**
+ * Check if we're within the recency window for last successful auth attempt.
+ */
+ internal fun wasRecentlyAuthenticated(maxRecencySeconds: Double): Boolean {
+ if (maxRecencySeconds <= 0.0) return false
+ val effectiveWindow = minOf(maxRecencySeconds, MAX_AUTH_RECENCY_WINDOW_SECONDS)
+ val last = lastSuccessfulAuthAtMs ?: return false
+ return SystemClock.elapsedRealtime() - last < (effectiveWindow * 1000).toLong()
+ }
+
+ // endregion
+
// region Composed Components
private val crypto = VaultCrypto(keystoreProvider, storageProvider)
internal val database = VaultDatabase(storageProvider, crypto)
private val itemRepository = net.aliasvault.app.vaultstore.repositories.ItemRepository(database)
internal val metadata = VaultMetadataManager(storageProvider)
- private val auth = VaultAuth(storageProvider) { cache.clearCache() }
+ private val auth = VaultAuth(
+ storageProvider,
+ onClearCache = {
+ cache.clearCache()
+ clearLastSuccessfulAuth()
+ },
+ onBackground = { clearLastSuccessfulAuth() },
+ )
private val sync = VaultSync(database, metadata, crypto, storageProvider, itemRepository)
private val mutate = VaultMutate(database, itemRepository, metadata, crypto, auth, storageProvider)
private val cache = VaultCache(crypto, database, keystoreProvider, storageProvider)
@@ -142,6 +186,7 @@ class VaultStore(
*/
fun clearEncryptionKeyFromMemory() {
crypto.clearEncryptionKeyFromMemory()
+ clearLastSuccessfulAuth()
}
/**
@@ -256,7 +301,12 @@ class VaultStore(
* Unlock the vault.
*/
fun unlockVault() {
+ // A nil-to-non-nil transition means the keystore just released the key after biometric.
+ val hadKeyInMemory = encryptionKey != null
database.unlockVault(auth.getAuthMethods())
+ if (!hadKeyInMemory && encryptionKey != null) {
+ markSuccessfulAuth()
+ }
}
/**
@@ -867,6 +917,7 @@ class VaultStore(
*/
fun clearCache() {
cache.clearCache()
+ clearLastSuccessfulAuth()
}
/**
@@ -877,6 +928,7 @@ class VaultStore(
*/
fun clearSession() {
cache.clearSession()
+ clearLastSuccessfulAuth()
}
/**
@@ -886,6 +938,7 @@ class VaultStore(
*/
fun clearVault() {
cache.clearVault()
+ clearLastSuccessfulAuth()
}
// endregion
@@ -926,7 +979,9 @@ class VaultStore(
*/
@Throws(Exception::class)
fun unlockWithPin(pinValue: String): String {
- return pin.unlockWithPin(pinValue)
+ val key = pin.unlockWithPin(pinValue)
+ markSuccessfulAuth()
+ return key
}
/**
diff --git a/apps/mobile-app/app/(tabs)/settings/mobile-unlock/[id].tsx b/apps/mobile-app/app/(tabs)/settings/mobile-unlock/[id].tsx
index 2048506b8..fb2e4667f 100644
--- a/apps/mobile-app/app/(tabs)/settings/mobile-unlock/[id].tsx
+++ b/apps/mobile-app/app/(tabs)/settings/mobile-unlock/[id].tsx
@@ -158,12 +158,13 @@ export default function MobileUnlockConfirmScreen() : React.ReactNode {
setIsProcessing(true);
try {
- /*
- * Mobile unlock is a security-sensitive operation that requires re-authentication.
- */
+ // Re-auth user for mobile login confirm if user has not authenticated within the last 10 seconds.
const authenticated = await VaultUnlockHelper.authenticateForAction(
t('settings.qrScanner.mobileLogin.confirmTitle'),
- t('settings.qrScanner.mobileLogin.confirmSubtitle')
+ t('settings.qrScanner.mobileLogin.confirmSubtitle'),
+ null,
+ null,
+ 10
);
if (!authenticated) {
diff --git a/apps/mobile-app/ios/NativeVaultManager/RCTNativeVaultManager.mm b/apps/mobile-app/ios/NativeVaultManager/RCTNativeVaultManager.mm
index bc196cbee..775671b24 100644
--- a/apps/mobile-app/ios/NativeVaultManager/RCTNativeVaultManager.mm
+++ b/apps/mobile-app/ios/NativeVaultManager/RCTNativeVaultManager.mm
@@ -321,8 +321,8 @@
// MARK: - Re-authentication
-- (void)authenticateUser:(NSString *)title subtitle:(NSString *)subtitle allowedMethods:(NSArray<NSString *> *)allowedMethods buttonText:(NSString *)buttonText resolve:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject {
- [vaultManager authenticateUser:title subtitle:subtitle allowedMethods:allowedMethods buttonText:buttonText resolver:resolve rejecter:reject];
+- (void)authenticateUser:(NSString *)title subtitle:(NSString *)subtitle allowedMethods:(NSArray<NSString *> *)allowedMethods buttonText:(NSString *)buttonText recentUnlockGraceSeconds:(double)recentUnlockGraceSeconds resolve:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject {
+ [vaultManager authenticateUser:title subtitle:subtitle allowedMethods:allowedMethods buttonText:buttonText recentUnlockGraceSeconds:recentUnlockGraceSeconds resolver:resolve rejecter:reject];
}
// MARK: - QR Code Scanner
diff --git a/apps/mobile-app/ios/NativeVaultManager/VaultManager.swift b/apps/mobile-app/ios/NativeVaultManager/VaultManager.swift
index 6b71c8b31..828581d7e 100644
--- a/apps/mobile-app/ios/NativeVaultManager/VaultManager.swift
+++ b/apps/mobile-app/ios/NativeVaultManager/VaultManager.swift
@@ -1054,8 +1054,14 @@ public class VaultManager: NSObject {
subtitle: String?,
allowedMethods: [String]?,
buttonText: String?,
+ recentUnlockGraceSeconds: Double,
resolver resolve: @escaping RCTPromiseResolveBlock,
rejecter reject: @escaping RCTPromiseRejectBlock) {
+ if vaultStore.wasRecentlyAuthenticated(recentUnlockGraceSeconds) {
+ resolve(true)
+ return
+ }
+
// Get enabled authentication methods
let authMethods = vaultStore.getAuthMethods()
let pinEnabled = vaultStore.isPinEnabled()
diff --git a/apps/mobile-app/ios/VaultStoreKit/VaultStore+Cache.swift b/apps/mobile-app/ios/VaultStoreKit/VaultStore+Cache.swift
index 652c1821f..916e6b01d 100644
--- a/apps/mobile-app/ios/VaultStoreKit/VaultStore+Cache.swift
+++ b/apps/mobile-app/ios/VaultStoreKit/VaultStore+Cache.swift
@@ -9,6 +9,7 @@ extension VaultStore {
print("Clearing cache - removing encryption key and decrypted database from memory")
self.encryptionKey = nil
self.dbConnection = nil
+ clearLastSuccessfulAuth()
}
/// Clear session data only (for forced logout).
@@ -21,6 +22,7 @@ extension VaultStore {
// Clear in-memory data only
self.encryptionKey = nil
self.dbConnection = nil
+ clearLastSuccessfulAuth()
// Clear biometric-protected key from keychain (user will need to re-authenticate)
do {
@@ -79,6 +81,7 @@ extension VaultStore {
self.enabledAuthMethods = []
self.autoLockTimeout = VaultConstants.defaultAutoLockTimeout
self.keyDerivationParams = nil
+ clearLastSuccessfulAuth()
}
/// Set the auto-lock timeout - the number of seconds after which the vault will be locked automatically
diff --git a/apps/mobile-app/ios/VaultStoreKit/VaultStore+Crypto.swift b/apps/mobile-app/ios/VaultStoreKit/VaultStore+Crypto.swift
index 0bcdfaa4c..41a2316b3 100644
--- a/apps/mobile-app/ios/VaultStoreKit/VaultStore+Crypto.swift
+++ b/apps/mobile-app/ios/VaultStoreKit/VaultStore+Crypto.swift
@@ -71,6 +71,7 @@ extension VaultStore {
/// This forces getEncryptionKey() to fetch from keychain on next access.
public func clearEncryptionKeyFromMemory() {
self.encryptionKey = nil
+ clearLastSuccessfulAuth()
print("Cleared encryption key from memory")
}
@@ -415,6 +416,7 @@ extension VaultStore {
}
}
+ markSuccessfulAuth()
return keyData
}
}
diff --git a/apps/mobile-app/ios/VaultStoreKit/VaultStore+Pin.swift b/apps/mobile-app/ios/VaultStoreKit/VaultStore+Pin.swift
index 0f3c8e158..c8147faac 100644
--- a/apps/mobile-app/ios/VaultStoreKit/VaultStore+Pin.swift
+++ b/apps/mobile-app/ios/VaultStoreKit/VaultStore+Pin.swift
@@ -109,6 +109,7 @@ extension VaultStore {
// Reset failed attempts on success
try storePinFailedAttemptsInKeychain(0)
+ markSuccessfulAuth()
// Return the decrypted vault encryption key as base64
return decryptedKey.base64EncodedString()
diff --git a/apps/mobile-app/ios/VaultStoreKit/VaultStore.swift b/apps/mobile-app/ios/VaultStoreKit/VaultStore.swift
index 8a374ae02..ccee24d0e 100644
--- a/apps/mobile-app/ios/VaultStoreKit/VaultStore.swift
+++ b/apps/mobile-app/ios/VaultStoreKit/VaultStore.swift
@@ -33,6 +33,15 @@ public class VaultStore {
/// The encryption key for the vault.
internal var encryptionKey: Data?
+ /// Last successful biometric/PIN auth operation.
+ private var lastSuccessfulAuthAt: TimeInterval?
+
+ /// Lock for accessing the last successful auth operation.
+ private let authRecencyLock = NSLock()
+
+ /// Maximum window of time for which a recent-auth grace can be honored, regardless of caller input.
+ private static let maxAuthRecencyWindowSeconds: Double = 15.0
+
/// The key derivation parameters used to derive the encryption key from the password.
internal var keyDerivationParams: String?
@@ -57,6 +66,34 @@ public class VaultStore {
return encryptionKey != nil
}
+ // MARK: - Authentication Recency
+
+ /// Mark successful authorization call to be used for future recency checks.
+ internal func markSuccessfulAuth() {
+ authRecencyLock.lock()
+ lastSuccessfulAuthAt = ProcessInfo.processInfo.systemUptime
+ authRecencyLock.unlock()
+ }
+
+ /// Invalidate the recency timestamp. Must be called whenever the encryption key is cleared
+ /// (lock, sign-out, auto-lock) so the grace window cannot outlive the unlocked state.
+ internal func clearLastSuccessfulAuth() {
+ authRecencyLock.lock()
+ lastSuccessfulAuthAt = nil
+ authRecencyLock.unlock()
+ }
+
+ /// Check if we're within the recency window for last successful auth attempt.
+ public func wasRecentlyAuthenticated(_ maxRecencySeconds: Double) -> Bool {
+ guard maxRecencySeconds > 0 else { return false }
+ let effectiveWindow = min(maxRecencySeconds, Self.maxAuthRecencyWindowSeconds)
+ authRecencyLock.lock()
+ let last = lastSuccessfulAuthAt
+ authRecencyLock.unlock()
+ guard let last = last else { return false }
+ return ProcessInfo.processInfo.systemUptime - last < effectiveWindow
+ }
+
/// Exclude the entire shared app group container from iCloud and iTunes backups.
/// All app data (encrypted vault database, UserDefaults plist with auth tokens and key
/// derivation parameters) is security-sensitive and device-bound. Note: actual encryption keys
@@ -107,6 +144,7 @@ public class VaultStore {
// MARK: - Background/Foreground Handling
@objc private func appDidEnterBackground() {
print("App entered background, starting auto-lock timer with \(autoLockTimeout) seconds")
+ clearLastSuccessfulAuth()
if self.autoLockTimeout > 0 {
self.clearCacheTimer = Timer.scheduledTimer(withTimeInterval: TimeInterval(self.autoLockTimeout), repeats: false) { [weak self] _ in
print("Auto-lock timer fired, clearing cache")
diff --git a/apps/mobile-app/specs/NativeVaultManager.ts b/apps/mobile-app/specs/NativeVaultManager.ts
index 21501d710..0431cf35e 100644
--- a/apps/mobile-app/specs/NativeVaultManager.ts
+++ b/apps/mobile-app/specs/NativeVaultManager.ts
@@ -125,7 +125,8 @@ export interface Spec extends TurboModule {
// Authenticate user with biometric or PIN. If title/subtitle are null/empty, defaults to "Unlock Vault" context.
// allowedMethods: Optional array of allowed methods ('biometric', 'pin', 'password'). If null/empty, all enabled methods are allowed.
// buttonText: Optional custom text for the unlock/confirm button. If null/empty, defaults to "Unlock".
- authenticateUser(title: string | null, subtitle: string | null, allowedMethods: string[] | null, buttonText: string | null): Promise<boolean>;
+ // recentUnlockGraceSeconds: If > 0, skip the prompt when a successful biometric or PIN unlock happened within this many seconds ago. Pass 0 to always prompt.
+ authenticateUser(title: string | null, subtitle: string | null, allowedMethods: string[] | null, buttonText: string | null, recentUnlockGraceSeconds: number): Promise<boolean>;
// QR code scanner
// Scan a QR code and return the scanned data. Returns null if cancelled or failed.
diff --git a/apps/mobile-app/utils/VaultUnlockHelper.ts b/apps/mobile-app/utils/VaultUnlockHelper.ts
index 2136b0001..51753e241 100644
--- a/apps/mobile-app/utils/VaultUnlockHelper.ts
+++ b/apps/mobile-app/utils/VaultUnlockHelper.ts
@@ -111,16 +111,18 @@ export class VaultUnlockHelper {
* @param subtitle Authentication prompt subtitle
* @param allowedMethods Optional array of allowed auth methods ('biometric', 'pin', 'password'). If null, all enabled methods are allowed.
* @param buttonText Optional custom text for the unlock/confirm button. If null, defaults to "Unlock".
+ * @param recentUnlockGraceSeconds If > 0, skip the prompt when the last biometric/PIN unlock was within this many seconds.
* @returns Promise<boolean> indicating if authentication succeeded
*/
static async authenticateForAction(
title: string,
subtitle: string,
allowedMethods: string[] | null = null,
- buttonText: string | null = null
+ buttonText: string | null = null,
+ recentUnlockGraceSeconds: number = 0
): Promise<boolean> {
try {
- const authenticated = await NativeVaultManager.authenticateUser(title, subtitle, allowedMethods, buttonText);
+ const authenticated = await NativeVaultManager.authenticateUser(title, subtitle, allowedMethods, buttonText, recentUnlockGraceSeconds);
return authenticated;
} catch (error) {
console.error('Authentication error:', error);