Privacy-first password manager with built-in email aliasing. Fully encrypted and self-hostable.
Use native auth confirm for shared folder delete confirm action (#2159)
Leendert de Borst311d11222689
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 dd53b3286..fb4762b24 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@@ -25,6 +25,7 @@ import kotlinx.coroutines.withContextimport net.aliasvault.app.qrscanner.QRScannerActivityimport net.aliasvault.app.vaultstore.AppErrorimport net.aliasvault.app.vaultstore.VaultStore+import net.aliasvault.app.vaultstore.interfaces.CryptoOperationCallbackimport net.aliasvault.app.vaultstore.keystoreprovider.AndroidKeystoreProviderimport net.aliasvault.app.vaultstore.storageprovider.AndroidStorageProviderimport net.aliasvault.app.webapi.WebApiService@@ -1997,6 +1998,37 @@ class NativeVaultManager(reactContext: ReactApplicationContext) :}}+ /**+ * Answer a server's SRP challenge with the unlock key of the open session (see VaultStore.deriveSrpProof).+ * @param salt The salt the initiate call returned.+ * @param srpIdentity The SRP identity the initiate call returned.+ * @param serverEphemeral The server public ephemeral the initiate call returned.+ * @param promise The promise to resolve with the client public ephemeral and session proof.+ */+ @ReactMethod+ override fun deriveSrpProof(salt: String, srpIdentity: String, serverEphemeral: String, promise: Promise) {+ vaultStore.deriveSrpProof(+ salt,+ srpIdentity,+ serverEphemeral,+ object : CryptoOperationCallback {+ override fun onSuccess(result: String) {+ val proof = JSONObject(result)+ val resultMap = Arguments.createMap().apply {+ putString("clientPublicEphemeral", proof.getString("clientPublicEphemeral"))+ putString("clientSessionProof", proof.getString("clientSessionProof"))+ }+ promise.resolve(resultMap)+ }++ override fun onError(e: Exception) {+ Log.e(TAG, "Error deriving the SRP proof", e)+ promise.reject("SRP_PROOF_ERROR", "Failed to derive the SRP proof: ${e.message}", e)+ }+ },+ )+ }+// MARK: - Sync State Management/**diff --git a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultCrypto.kt b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultCrypto.ktindex ebe657403..f79798e5b 100644--- a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultCrypto.kt+++ b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultCrypto.kt@@ -7,6 +7,9 @@ import net.aliasvault.app.vaultstore.keystoreprovider.KeystoreOperationCallbackimport net.aliasvault.app.vaultstore.keystoreprovider.KeystoreProviderimport net.aliasvault.app.vaultstore.storageprovider.StorageProviderimport org.json.JSONObject+import uniffi.aliasvault_core.srpDerivePrivateKey+import uniffi.aliasvault_core.srpDeriveSession+import uniffi.aliasvault_core.srpGenerateEphemeralimport java.math.BigIntegerimport java.security.SecureRandomimport javax.crypto.Cipher@@ -282,6 +285,33 @@ class VaultCrypto(withSession(callback, authMethods) { unlockKey }}+ /**+ * Answer a server's SRP challenge with the available unlock key.+ */+ fun deriveSrpProof(salt: String, srpIdentity: String, serverEphemeral: String, callback: CryptoOperationCallback, authMethods: String) {+ withSession(+ object : CryptoOperationCallback {+ override fun onSuccess(result: String) {+ try {+ val passwordHash = Base64.decode(result, Base64.NO_WRAP).joinToString("") { "%02X".format(it) }+ val ephemeral = srpGenerateEphemeral()+ val privateKey = srpDerivePrivateKey(salt, srpIdentity, passwordHash)+ val session = srpDeriveSession(ephemeral.secret, serverEphemeral, salt, srpIdentity, privateKey)+ callback.onSuccess(JSONObject().put("clientPublicEphemeral", ephemeral.public).put("clientSessionProof", session.proof).toString())+ } catch (e: Exception) {+ Log.e(TAG, "Could not derive the SRP proof from the unlock key", e)+ callback.onError(e)+ }+ }++ override fun onError(e: Exception) {+ callback.onError(e)+ }+ },+ authMethods,+ ) { unlockKey }+ }+/*** Hand one of the session keys to the callback, opening the session from the keystore behind a biometric prompt* when none is open.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.ktindex 7bf32bbf5..f6d41fdbe 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@@ -201,6 +201,13 @@ class VaultStore(crypto.getUnlockKey(callback, auth.getAuthMethods())}+ /**+ * Answer a server's SRP challenge with the unlock key of the open session (see VaultCrypto.deriveSrpProof).+ */+ fun deriveSrpProof(salt: String, srpIdentity: String, serverEphemeral: String, callback: CryptoOperationCallback) {+ crypto.deriveSrpProof(salt, srpIdentity, serverEphemeral, callback, auth.getAuthMethods())+ }+/*** Check if biometric authentication is enabled and available.*/diff --git a/apps/mobile-app/app/(tabs)/settings/family-sharing.tsx b/apps/mobile-app/app/(tabs)/settings/family-sharing.tsxindex 842904053..0c17ef5a5 100644--- a/apps/mobile-app/app/(tabs)/settings/family-sharing.tsx+++ b/apps/mobile-app/app/(tabs)/settings/family-sharing.tsx@@ -1,7 +1,4 @@-import { Buffer } from 'buffer';-import { ApiRequestError } from '@aliasvault/client/api/errors/ApiRequestError';-import { SrpAuthService } from '@aliasvault/client/auth/SrpAuthService';import { canAdministerGroup, describeMemberAccess, holdsManifestKey, ownUserIdIn, roleTranslationKey, sharingErrorTranslationKey } from '@aliasvault/client/sharing/FamilySharingView';import { multiManifestRendering } from '@aliasvault/client/sharing/MultiManifestRendering';import { SharingService } from '@aliasvault/client/sharing/SharingService';@@ -13,12 +10,12 @@ import { useTranslation } from 'react-i18next';import { RefreshControl, StyleSheet, TextInput, TouchableOpacity, View } from 'react-native';import { HapticsUtility } from '@/utils/HapticsUtility';+import { VaultUnlockHelper } from '@/utils/VaultUnlockHelper';import { useColors } from '@/hooks/useColorScheme';import { useMinDurationLoading } from '@/hooks/useMinDurationLoading';import { useVaultSync } from '@/hooks/useVaultSync';-import { ConfirmPasswordModal } from '@/components/common/ConfirmPasswordModal';import { ThemedContainer } from '@/components/themed/ThemedContainer';import { ThemedScrollView } from '@/components/themed/ThemedScrollView';import { ThemedText } from '@/components/themed/ThemedText';@@ -32,11 +29,6 @@ import NativeVaultManager from '@/specs/NativeVaultManager';import type { GroupInfo, GroupMemberInfo, GroupOverviewResponse, SharedManifestInfo } from '@aliasvault/models/webapi';-/**- * The shared folder the password confirmation is about to delete.- */-type PendingVaultDelete = { group: GroupInfo; manifest: SharedManifestInfo };-/** A sharing operation that failed with a reason already put into words for the user. */class SharingOperationError extends Error {}@@ -48,7 +40,7 @@ export default function FamilySharingScreen(): React.ReactNode {const colors = useColors();const webApi = useWebApi();const { t } = useTranslation();- const { username, verifyPassword } = useApp();+ const { username } = useApp();const { sqliteClient } = useDb();const { isEnabled, isLoaded } = useCapabilityContext();const { showConfirm } = useDialog();@@ -63,7 +55,6 @@ export default function FamilySharingScreen(): React.ReactNode {const [isLoading, setIsLoading] = useMinDurationLoading(true, 200);const [isRefreshing, setIsRefreshing] = useMinDurationLoading(false, 200);const [expandedRosters, setExpandedRosters] = useState<Record<string, boolean>>({});- const [pendingVaultDelete, setPendingVaultDelete] = useState<PendingVaultDelete | null>(null);const [newVaultNames, setNewVaultNames] = useState<Record<string, string>>({});/**@@ -219,54 +210,47 @@ export default function FamilySharingScreen(): React.ReactNode {};/**- * Ask before deleting a shared folder, then move on to the master password confirmation.+ * Delete a shared folder behind the native password prompt. The server wants proof of the master password, which+ * the native layer answers with the unlock key of the open session.+ * @param group - the group the shared folder belongs to.+ * @param manifest - the shared folder to delete.*/- const confirmVaultDelete = (group: GroupInfo, manifest: SharedManifestInfo): void => {- showConfirm(- t('sharing.family.deleteVault'),- t('sharing.family.deleteVaultConfirm', { vault: vaultLabel(manifest) }),- t('common.delete'),- () => setPendingVaultDelete({ group, manifest }),- { confirmStyle: 'destructive' }- );- };-- /**- * Delete a shared folder, proving the master password to the server the way the account deletion does.- * @param password - the entered master password.- */- const deleteSharedVault = async (password: string): Promise<void> => {- const target = pendingVaultDelete;- if (!target) {+ const deleteSharedVault = async (group: GroupInfo, manifest: SharedManifestInfo): Promise<void> => {+ const authenticated = await VaultUnlockHelper.authenticateForAction(t('sharing.family.deleteVault'), t('settings.passwordConfirm.description'), null, t('common.delete'));+ if (!authenticated) {return;}- const passwordHashBase64 = await verifyPassword(password);- if (!passwordHashBase64) {- throw new Error(t('auth.errors.incorrectPassword'));- }-- try {- await SharingService.deleteSharedManifest(webApi, target.group.groupId, target.manifest.manifestId, async (challenge) => {- const passwordHashString = Buffer.from(passwordHashBase64, 'base64').toString('hex').toUpperCase();- const proof = await SrpAuthService.deriveClientProof(challenge.salt, challenge.srpIdentity, passwordHashString, challenge.serverEphemeral);- return { clientPublicEphemeral: proof.clientPublicEphemeral, clientSessionProof: proof.clientSessionProof };- });- } catch (deleteError) {- if (deleteError instanceof ApiRequestError && deleteError.apiErrorCode === 'PASSWORD_MISMATCH') {- throw new Error(t('auth.errors.incorrectPassword'));+ await run(async () => {+ try {+ await SharingService.deleteSharedManifest(webApi, group.groupId, manifest.manifestId, challenge => NativeVaultManager.deriveSrpProof(challenge.salt, challenge.srpIdentity, challenge.serverEphemeral));+ } catch (deleteError) {+ // Local unlock key could mismatch what is actually stored on server (recent password change on other device), if so we show a incorrect password error.+ if (deleteError instanceof ApiRequestError && deleteError.apiErrorCode === 'PASSWORD_MISMATCH') {+ throw new SharingOperationError(t('auth.errors.incorrectPassword'));+ }++ throw deleteError;}- throw new Error(apiErrorMessage(deleteError, t('sharing.family.errors.deleteVaultFailed')));- }-- setPendingVaultDelete(null);- await run(async () => {await syncVault();setNotice(t('sharing.family.vaultDeleted'));}, t('sharing.family.errors.deleteVaultFailed'));};+ /**+ * Ask before deleting a shared folder, then move on to the native master password prompt.+ */+ const confirmVaultDelete = (group: GroupInfo, manifest: SharedManifestInfo): void => {+ showConfirm(+ t('sharing.family.deleteVault'),+ t('sharing.family.deleteVaultConfirm', { vault: vaultLabel(manifest) }),+ t('common.delete'),+ () => deleteSharedVault(group, manifest),+ { confirmStyle: 'destructive' }+ );+ };+/*** Refresh on pull to refresh.*/@@ -439,15 +423,6 @@ export default function FamilySharingScreen(): React.ReactNode {return (<ThemedContainer>- <ConfirmPasswordModal- isOpen={pendingVaultDelete !== null}- onClose={() => setPendingVaultDelete(null)}- onConfirm={deleteSharedVault}- title={t('sharing.family.deleteVault')}- message={t('sharing.family.deleteVaultPasswordPrompt', { vault: pendingVaultDelete ? vaultLabel(pendingVaultDelete.manifest) : '' })}- confirmText={t('common.delete')}- />-<ThemedScrollView refreshControl={<RefreshControl refreshing={isRefreshing} onRefresh={onRefresh} colors={[colors.primary]} tintColor={colors.primary} />}><View style={styles.headerRow}><ThemedText style={styles.headerText}>{t('sharing.family.description')}</ThemedText>diff --git a/apps/mobile-app/i18n/locales/en.json b/apps/mobile-app/i18n/locales/en.jsonindex 2f15c042f..39e4e6c96 100644--- a/apps/mobile-app/i18n/locales/en.json+++ b/apps/mobile-app/i18n/locales/en.json@@ -193,6 +193,7 @@"exportConfirmTitle": "Export Vault","exportWarning": "Warning: Exporting your vault to an unencrypted file will expose all of your passwords and sensitive information in plain text. Only do this on trusted devices and ensure you:\n\n• Store the exported file in a secure location\n• Delete the file when you no longer need it\n• Never share the exported file with others\n\nAre you sure you want to continue with the export?","passwordConfirm": {+ "description": "For security reasons, please enter your master password to confirm this action.","exportDescription": "For security reasons, please enter your master password to confirm this export."},"security": "Security",@@ -388,7 +389,6 @@"revokeAccessWarning": "They keep any copy of this folder they already downloaded. Change the passwords in it that you do not want them to keep using.","deleteVault": "Delete folder","deleteVaultConfirm": "Permanently delete “{{vault}}”? Every member of the family loses this folder and everything in it. This cannot be undone.",- "deleteVaultPasswordPrompt": "Enter your master password to confirm deleting “{{vault}}” for the whole family.","vaultDeleted": "The shared folder has been deleted.","unnamedVault": "Shared folder"}diff --git a/apps/mobile-app/ios/NativeVaultManager/RCTNativeVaultManager.mm b/apps/mobile-app/ios/NativeVaultManager/RCTNativeVaultManager.mmindex fe2f624c4..fca853be4 100644--- a/apps/mobile-app/ios/NativeVaultManager/RCTNativeVaultManager.mm+++ b/apps/mobile-app/ios/NativeVaultManager/RCTNativeVaultManager.mm@@ -369,6 +369,10 @@[vaultManager authenticateUser:title subtitle:subtitle allowedMethods:allowedMethods buttonText:buttonText recentUnlockGraceSeconds:recentUnlockGraceSeconds resolver:resolve rejecter:reject];}+- (void)deriveSrpProof:(NSString *)salt srpIdentity:(NSString *)srpIdentity serverEphemeral:(NSString *)serverEphemeral resolve:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject {+ [vaultManager deriveSrpProof:salt srpIdentity:srpIdentity serverEphemeral:serverEphemeral resolver:resolve rejecter:reject];+}+// MARK: - QR Code Scanner- (void)scanQRCode:(NSArray<NSString *> *)prefixes statusText:(NSString *)statusText resolve:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject {diff --git a/apps/mobile-app/ios/NativeVaultManager/VaultManager.swift b/apps/mobile-app/ios/NativeVaultManager/VaultManager.swiftindex db3b2b297..a374bd18d 100644--- a/apps/mobile-app/ios/NativeVaultManager/VaultManager.swift+++ b/apps/mobile-app/ios/NativeVaultManager/VaultManager.swift@@ -1423,6 +1423,28 @@ public class VaultManager: NSObject {}}+ /// Answer a server's SRP challenge with the unlock key of the open session (see VaultStore.deriveSrpProof).+ @objc+ func deriveSrpProof(_ salt: String,+ srpIdentity: String,+ serverEphemeral: String,+ resolver resolve: @escaping RCTPromiseResolveBlock,+ rejecter reject: @escaping RCTPromiseRejectBlock) {+ DispatchQueue.global(qos: .userInitiated).async { [weak self] in+ guard let self = self else {+ reject("INTERNAL_ERROR", "VaultManager instance deallocated", nil)+ return+ }++ do {+ let proof = try self.vaultStore.deriveSrpProof(salt: salt, srpIdentity: srpIdentity, serverEphemeral: serverEphemeral)+ resolve(["clientPublicEphemeral": proof.clientPublicEphemeral, "clientSessionProof": proof.clientSessionProof])+ } catch {+ reject("SRP_PROOF_ERROR", "Failed to derive the SRP proof: \(error.localizedDescription)", error)+ }+ }+ }+// MARK: - Sync State Management@objcdiff --git a/apps/mobile-app/ios/VaultStoreKit/VaultStore+Crypto.swift b/apps/mobile-app/ios/VaultStoreKit/VaultStore+Crypto.swiftindex f44a2e13d..85535ae99 100644--- a/apps/mobile-app/ios/VaultStoreKit/VaultStore+Crypto.swift+++ b/apps/mobile-app/ios/VaultStoreKit/VaultStore+Crypto.swift@@ -179,6 +179,15 @@ extension VaultStore {}}+ /// Answer a server's SRP challenge with the unlock key of the open session.+ public func deriveSrpProof(salt: String, srpIdentity: String, serverEphemeral: String) throws -> (clientPublicEphemeral: String, clientSessionProof: String) {+ let passwordHash = try getUnlockKey().map { String(format: "%02X", $0) }.joined()+ let ephemeral = RustCoreFramework.srpGenerateEphemeral()+ let privateKey = try RustCoreFramework.srpDerivePrivateKey(salt: salt, identity: srpIdentity, passwordHash: passwordHash)+ let session = try RustCoreFramework.srpDeriveSession(clientSecret: ephemeral.secret, serverPublic: serverEphemeral, salt: salt, identity: srpIdentity, privateKey: privateKey)+ return (ephemeral.public, session.proof)+ }+/// Encrypt the data using the encryption keyinternal func encrypt(data: Data) throws -> Data {let encryptionKey = try getEncryptionKey()diff --git a/apps/mobile-app/specs/NativeVaultManager.ts b/apps/mobile-app/specs/NativeVaultManager.tsindex 1e4705ec1..8e7077431 100644--- a/apps/mobile-app/specs/NativeVaultManager.ts+++ b/apps/mobile-app/specs/NativeVaultManager.ts@@ -153,6 +153,9 @@ export interface Spec extends TurboModule {// 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>;+ // Answer a server's SRP challenge with the available unlock key.+ deriveSrpProof(salt: string, srpIdentity: string, serverEphemeral: string): Promise<{ clientPublicEphemeral: string; clientSessionProof: string }>;+// QR code scanner// Scan a QR code and return the scanned data. Returns null if cancelled or failed.// If prefixes is provided, only QR codes starting with one of these prefixes will be accepted.