Privacy-first password manager with built-in email aliasing. Fully encrypted and self-hostable.
Add explicit open keychain for unlock key and account key methods
Leendert de Borstccffe43dc202
diff --git a/apps/browser-extension/src/entrypoints/background/AuthHandler.ts b/apps/browser-extension/src/entrypoints/background/AuthHandler.tsindex b45e8c25f..71d442017 100644--- a/apps/browser-extension/src/entrypoints/background/AuthHandler.ts+++ b/apps/browser-extension/src/entrypoints/background/AuthHandler.ts@@ -7,7 +7,6 @@ import { describeAuthError, type AuthErrorOptions } from '@aliasvault/client/autimport { SrpAuthService } from '@aliasvault/client/auth/SrpAuthService';import { SrpLoginService } from '@aliasvault/client/auth/SrpLoginService';import { MissingDerivationParamsError, UnlockService } from '@aliasvault/client/auth/UnlockService';-import { VaultKeyService } from '@aliasvault/client/auth/VaultKeyService';import { logoutReasonKey } from '@aliasvault/client/sync/VaultSync';import { handleClearTwoFactorState, handleGetTwoFactorState, handleStoreTwoFactorState } from '@/entrypoints/background/TwoFactorStateHandler';@@ -15,7 +14,7 @@ import { handleClearSession, handleFullVaultSync, handleStoreAccountKey } from 'import { StorageKeys } from '@/utils/constants/storageKeys';import { logExpected, logFailure } from '@/utils/Diagnostics';-import { convertLegacyPinKey } from '@/utils/LegacyKeyConversion';+import { accountKeyFromPinKey } from '@/utils/LegacyKeyConversion';import { LocalPreferencesService } from '@/utils/LocalPreferencesService';import { sendMessage } from '@/utils/messaging/ExtensionMessaging';import { IncorrectPinError, InvalidPinFormatError, PinLockedError, removeAndDisablePin, resetFailedAttempts, unlockWithPin } from '@/utils/PinUnlockService';@@ -190,8 +189,8 @@ export function handleUnlockWithPin(data: { pin: string }): Promise<BackgroundAureturn runExclusive(async () => {try {const pinKey = await unlockWithPin(data.pin);- const accountKey = await VaultKeyService.verifyUnlockKey(pinKey);- await convertLegacyPinKey(data.pin, pinKey, accountKey);+ // This legacy key conversion call can be removed once all clients have updated to 0.31.0+.+ const accountKey = await accountKeyFromPinKey(data.pin, pinKey);const status = await checkServerStatus(new WebApiService());if ('logout' in status) {@@ -293,7 +292,7 @@ async function completeLogin(username: string, token: string, refreshToken: stri// Fetch the key chain and check the unlock key opens it. Not recoverable when it fails, so log out again.const webApi = new WebApiService();- await UnlockService.completeKeyChainLogin(unlockKey, derivationParams, webApi, async () => {+ await UnlockService.completeKeyChainLogin({ unlockKey }, derivationParams, webApi, async () => {await webApi.revokeTokens();await handleClearSession();});diff --git a/apps/browser-extension/src/entrypoints/popup/pages/auth/Login.tsx b/apps/browser-extension/src/entrypoints/popup/pages/auth/Login.tsxindex 822a4685a..6a858ebd7 100644--- a/apps/browser-extension/src/entrypoints/popup/pages/auth/Login.tsx+++ b/apps/browser-extension/src/entrypoints/popup/pages/auth/Login.tsx@@ -186,7 +186,7 @@ const Login: React.FC = () => {*/let accountKey: string;try {- accountKey = await VaultKeyService.refreshKeyChain(unlockKey, webApi);+ accountKey = await VaultKeyService.refreshKeyChain({ unlockKey }, webApi);} catch (err) {// If key chain can't be fetched, logout user and show error as this is not a recoverable error.await app.logout();diff --git a/apps/browser-extension/src/entrypoints/popup/pages/auth/Unlock.tsx b/apps/browser-extension/src/entrypoints/popup/pages/auth/Unlock.tsxindex 41afe0895..8f8bb1e59 100644--- a/apps/browser-extension/src/entrypoints/popup/pages/auth/Unlock.tsx+++ b/apps/browser-extension/src/entrypoints/popup/pages/auth/Unlock.tsx@@ -471,7 +471,7 @@ const Unlock: React.FC = () => {await authContext.setAuthTokens(result.username, result.token, result.refreshToken);// The mobile device sends its stored key.- const accountKey = await VaultKeyService.refreshKeyChain(result.accountKey, webApi);+ const accountKey = await VaultKeyService.refreshKeyChain({ accountKey: result.accountKey }, webApi);// Store the Account Key and derivation paramsawait dbContext.storeAccountKey(accountKey);diff --git a/apps/browser-extension/src/utils/LegacyKeyConversion.ts b/apps/browser-extension/src/utils/LegacyKeyConversion.tsindex ded3d4ef6..e7109cbb0 100644--- a/apps/browser-extension/src/utils/LegacyKeyConversion.ts+++ b/apps/browser-extension/src/utils/LegacyKeyConversion.ts@@ -1,23 +1,35 @@+import { AppErrorCode, extractErrorCode } from '@aliasvault/client/api/errors/AppErrorCodes';+import { VaultKeyService } from '@aliasvault/client/auth/VaultKeyService';+import { setupPin } from '@/utils/PinUnlockService';/*- * Legacy conversion of a stored unlock key to the Account Key.+ * Legacy conversion of a PIN that protects an unlock key to one that protects the Account Key.** Before 0.31.0 the PIN protected the unlock key (the Argon2id output of the master password). Since then it protects- * the Account Key. A PIN set up before the account had a key chain still opens the chain; it is then re-encrypted- * with the Account Key, once. The stored Account Key itself converts in core/client `convertLegacySessionKey`.+ * the Account Key. A PIN set up before the account had a key chain still opens the chain, as an unlock key; it is then+ * re-encrypted with the Account Key, once. The session's own stored key converts in core/client `convertLegacySessionKey`.*- * TODO: remove once accounts without a key chain (pre-0.31.0) are no longer supported.+ * TODO: remove once accounts without a key chain (pre-0.31.0) are no longer supported; `accountKeyFromPinKey` then+ * becomes `VaultKeyService.verifyAccountKey`.*//**- * Re-encrypt the PIN with the Account Key when it still protected an unlock key.+ * The Account Key a PIN protects, checked against the cached key chain.* @param pin - the PIN the user just unlocked with- * @param pinKey - the key the PIN protected- * @param accountKey - the Account Key the chain opened with it+ * @param pinKey - the key the PIN protected: the Account Key, or an unlock key for a PIN set before the account had a key chain*/-export async function convertLegacyPinKey(pin: string, pinKey: string, accountKey: string): Promise<void> {- if (accountKey !== pinKey) {- await setupPin(pin, accountKey);+export async function accountKeyFromPinKey(pin: string, pinKey: string): Promise<string> {+ try {+ return await VaultKeyService.verifyAccountKey(pinKey);+ } catch (error) {+ if (!(error instanceof Error) || extractErrorCode(error.message) !== AppErrorCode.UNLOCK_KEY_REJECTED) {+ throw error;+ }}++ // LEGACY: the PIN protects an unlock key; the chain opens with it as such and the PIN is re-encrypted with the Account Key.+ const accountKey = await VaultKeyService.verifyUnlockKey(pinKey);+ await setupPin(pin, accountKey);+ return accountKey;}diff --git a/apps/browser-extension/tests/helpers/manifest-v2-api.ts b/apps/browser-extension/tests/helpers/manifest-v2-api.tsindex 686adade4..0da0695b4 100644--- a/apps/browser-extension/tests/helpers/manifest-v2-api.ts+++ b/apps/browser-extension/tests/helpers/manifest-v2-api.ts@@ -10,7 +10,7 @@import { createHash } from 'crypto';import { SrpAuthService } from '@aliasvault/client/auth/SrpAuthService';-import { getSyncableTableNames, openAccountKeyChain, vaultCodecCanonicalizeFromSqlite, vaultCodecGenerateManifestSalt, vaultCodecPackPayload, vaultCodecUnpackPayload } from '@aliasvault/client/rust/RustCore';+import { getSyncableTableNames, openKeyChainWithUnlockKey, vaultCodecCanonicalizeFromSqlite, vaultCodecGenerateManifestSalt, vaultCodecPackPayload, vaultCodecUnpackPayload } from '@aliasvault/client/rust/RustCore';import { bucketAad, manifestAad, symmetricDecryptBytes, symmetricEncryptBytes } from './vault-crypto';@@ -140,7 +140,7 @@ export async function resolveVaultEncryptionKey(apiBaseUrl: string, token: strinthrow new Error('Vault key chain is missing the encrypted VEK');}- const opened = await openAccountKeyChain(Buffer.from(derivedKey).toString('base64'), vaultKey.encryptedAccountKey, vaultKey.encryptedVek, null);+ const opened = await openKeyChainWithUnlockKey(Buffer.from(derivedKey).toString('base64'), vaultKey.encryptedAccountKey, vaultKey.encryptedVek, null);if (opened.status !== 'opened') {throw new Error(`Vault key chain did not open: ${opened.status}`);}diff --git a/apps/browser-extension/tests/helpers/test-api.ts b/apps/browser-extension/tests/helpers/test-api.tsindex 466414bd7..f93980bd7 100644--- a/apps/browser-extension/tests/helpers/test-api.ts+++ b/apps/browser-extension/tests/helpers/test-api.ts@@ -69,11 +69,11 @@ export async function registerTestUser(): Promise<{ tokenModel: TokenModel; encryptionKey: Uint8Array }> {const baseUrl = WebApiService.versionedBaseUrl(apiBaseUrl);const auth = new SrpLoginService({ rawFetch: (endpoint, options) => fetch(`${baseUrl}${endpoint}`, options) });- const { token, keys, derivedKey } = await auth.register(username, password);+ const { token, keys, unlockKey } = await auth.register(username, password);await pushInitialVault(apiBaseUrl, token.token, username, base64ToBytes(keys.vaultEncryptionKey));- return { tokenModel: token, encryptionKey: base64ToBytes(derivedKey) };+ return { tokenModel: token, encryptionKey: base64ToBytes(unlockKey) };}/**diff --git a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/MainActivity.kt b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/MainActivity.ktindex 64fbb1203..89faf6026 100644--- a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/MainActivity.kt+++ b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/MainActivity.kt@@ -271,8 +271,8 @@ class MainActivity : ReactActivity() {// Run on IO thread to avoid blocking main threadkotlinx.coroutines.CoroutineScope(kotlinx.coroutines.Dispatchers.IO).launch {try {- // Store unlock key in memory only- vaultStore.storeAccountKeyInMemory(unlockKeyBase64)+ // Open the session with the unlock key, in memory only+ vaultStore.openSessionWithUnlockKey(unlockKeyBase64, persistToKeystore = false)// Unlock the vault with the key now in memoryvaultStore.unlockVault()diff --git a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/credentialprovider/UnlockCoordinator.kt b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/credentialprovider/UnlockCoordinator.ktindex e6075de59..770687cdb 100644--- a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/credentialprovider/UnlockCoordinator.kt+++ b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/credentialprovider/UnlockCoordinator.kt@@ -102,7 +102,7 @@ class UnlockCoordinator(override fun onSuccess(result: String) {try {// Biometric authentication successful, unlock vault- vaultStore.storeAccountKeyInMemory(result)+ vaultStore.openSessionWithStoredKey(result)vaultStore.unlockVault()// Notify success@@ -177,7 +177,7 @@ class UnlockCoordinator(val unlockKey = data?.getStringExtra(PasswordUnlockActivity.EXTRA_UNLOCK_KEY)if (unlockKey != null) {try {- vaultStore.storeAccountKeyInMemory(unlockKey)+ vaultStore.openSessionWithUnlockKey(unlockKey, persistToKeystore = false)vaultStore.unlockVault()onUnlocked()} catch (e: Exception) {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 4b02f9d7d..2e83e6cf1 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@@ -249,35 +249,20 @@ class NativeVaultManager(reactContext: ReactApplicationContext) :}/**- * Open a session in memory with the unlock key or the Account Key, without keystore persistence.- * Use this to test if a key is valid before persisting.- * @param base64Key The unlock key or Account Key as a base64 encoded string+ * Open a session with the unlock key of a password login; with [persistToKeychain] the Account Key it yields is also+ * stored in the keystore when biometrics are enabled (may trigger a biometric prompt).+ * @param unlockKeyBase64 The unlock key as a base64 encoded string+ * @param persistToKeychain Whether to also persist the Account Key to the keystore* @param promise The promise to resolve*/@ReactMethod- override fun storeAccountKeyInMemory(base64Key: String, promise: Promise) {+ override fun openSessionWithUnlockKey(unlockKeyBase64: String, persistToKeychain: Boolean, promise: Promise) {try {- vaultStore.storeAccountKeyInMemory(base64Key)+ vaultStore.openSessionWithUnlockKey(unlockKeyBase64, persistToKeychain)promise.resolve(null)} catch (e: Exception) {- Log.e(TAG, "Error storing Account Key in memory", e)- promise.reject("ERR_STORE_KEY_MEMORY", "Failed to store Account Key in memory: ${e.message}", e)- }- }-- /**- * Open a session with the unlock key or the Account Key AND persist the Account Key to keystore (may trigger biometric prompt).- * @param base64Key The unlock key or Account Key as a base64 encoded string- * @param promise The promise to resolve- */- @ReactMethod- override fun storeAccountKey(base64Key: String, promise: Promise) {- try {- vaultStore.storeAccountKey(base64Key)- promise.resolve(null)- } catch (e: Exception) {- Log.e(TAG, "Error storing Account Key", e)- promise.reject("ERR_STORE_KEY", "Failed to store Account Key: ${e.message}", e)+ Log.e(TAG, "Error opening the session with the unlock key", e)+ promise.reject("ERR_OPEN_SESSION", "Failed to open the session with the unlock key: ${e.message}", e)}}diff --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 27d20019a..99f9ea6c1 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@@ -26,7 +26,9 @@ import uniffi.aliasvault_core.isRelatedOriginAllowedimport uniffi.aliasvault_core.isRpIdAllowedForHostimport uniffi.aliasvault_core.mobileLoginPublicKeyHashimport uniffi.aliasvault_core.mobileLoginVerificationCode-import uniffi.aliasvault_core.openAccountKeyChain+import uniffi.aliasvault_core.KeyChainKeys+import uniffi.aliasvault_core.openKeyChainWithAccountKey+import uniffi.aliasvault_core.openKeyChainWithUnlockKeyimport uniffi.aliasvault_core.parseEmailSourceimport uniffi.aliasvault_core.reencryptAccountKeyJsonimport uniffi.aliasvault_core.rsaDecrypt@@ -96,7 +98,8 @@ object RustCoreDispatcher {"argon2DeriveKey" -> json(argon2DeriveKey(args.string(0), args.string(1), args.string(2)))"deriveSrpPasswordHash" -> json(deriveSrpPasswordHash(args.bytes(0), args.string(1)))- "openAccountKeyChain" -> openKeyChain(args.bytes(0), args.string(1), args.string(2), args.optionalString(3))+ "openKeyChainWithUnlockKey" -> keyChainResult { openKeyChainWithUnlockKey(args.bytes(0), args.string(1), args.string(2), args.optionalString(3)) }+ "openKeyChainWithAccountKey" -> keyChainResult { openKeyChainWithAccountKey(args.bytes(0), args.string(1), args.optionalString(2)) }"createAccountKeyHierarchyJson" -> createAccountKeyHierarchyJson(args.bytes(0), args.string(1), args.string(2))"reencryptAccountKeyJson" -> reencryptAccountKeyJson(args.string(0), args.bytes(1), args.bytes(2))@@ -154,18 +157,20 @@ object RustCoreDispatcher {/** JSON-encode a list of strings. */private fun json(values: List<String>): String = JSONArray(values).toString()- /** Open a key chain and report the outcome as the `KeyChainOpenResult` JSON the client core expects. */+ /** Open a key chain through [open] and report the outcome as the `KeyChainOpenResult` JSON the client core expects. */@Suppress("SwallowedException") // A failure is reported as its status, not thrown.- private fun openKeyChain(key: ByteArray, encryptedAccountKey: String, encryptedVek: String, encryptedAccountPrivateKey: String?): String {+ private fun keyChainResult(open: () -> KeyChainKeys): String {val result = JSONObject()try {- val keys = openAccountKeyChain(key, encryptedAccountKey, encryptedVek, encryptedAccountPrivateKey)+ val keys = open()result.put("status", "opened").put("vaultEncryptionKey", Base64.encodeToString(keys.vaultEncryptionKey, Base64.NO_WRAP)).put("accountKey", Base64.encodeToString(keys.accountKey, Base64.NO_WRAP)).put("accountPrivateKey", keys.accountPrivateKey ?: JSONObject.NULL)} catch (e: KeyChainException.UnlockKeyRejected) {result.put("status", "unlockKeyRejected")+ } catch (e: KeyChainException.AccountKeyRejected) {+ result.put("status", "accountKeyRejected")} catch (e: KeyChainException.KeyChainUnreadable) {result.put("status", "keyChainUnreadable").put("message", e.message ?: "")}diff --git a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/LegacyKeyConversion.kt b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/LegacyKeyConversion.ktindex 57e319c0f..aa341130b 100644--- a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/LegacyKeyConversion.kt+++ b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/LegacyKeyConversion.kt@@ -10,14 +10,30 @@ import net.aliasvault.app.vaultstore.keystoreprovider.KeystoreProvider** The keystore and the PIN protect the Account Key, the one secret an unlocked session holds. Before 0.31.0 they* protected the unlock key (the Argon2id output of the master password). A key stored then (a 0.30.x install, or an- * account upgraded on another device) still opens the account key chain, which yields the Account Key; these helpers- * then store the Account Key in its place, once. For an account without a key chain the stored key is the vault key.+ * account upgraded on another device) still opens the account key chain, as an unlock key; these helpers then store the+ * Account Key in its place, once. For an account without a key chain the stored key is the vault key.*- * TODO: remove once accounts without a key chain (pre-0.31.0) are no longer supported.+ * Other platform implementations: VaultStore+LegacyKeyConversion.swift (iOS), LegacyKeyConversion.ts (core/client and browser extension).+ *+ * TODO: remove once accounts without a key chain (pre-0.31.0) are no longer supported; [openStoredKey] then becomes+ * [VaultCrypto.openKeyChainWithAccountKey].*/internal object LegacyKeyConversion {private const val TAG = "LegacyKeyConversion"+ /**+ * Open the cached account key chain with a key the keystore, the PIN or the session stored: the Account Key, or the+ * unlock key a store written before the account had a key chain holds.+ */+ fun openStoredKey(crypto: VaultCrypto, key: ByteArray): VaultCrypto.SessionKeys {+ return try {+ crypto.openKeyChainWithAccountKey(key)+ } catch (e: AppError.UnlockKeyRejected) {+ // LEGACY: the stored key is an unlock key; the caller stores the Account Key the chain yields in its place.+ crypto.openKeyChainWithUnlockKey(key)+ }+ }+/*** Re-encrypt the PIN with the Account Key when it still protected an unlock key.*/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 00a1266aa..45fcde83b 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@@ -8,8 +8,10 @@ import net.aliasvault.app.vaultstore.keystoreprovider.KeystoreProviderimport net.aliasvault.app.vaultstore.storageprovider.StorageProviderimport org.json.JSONObjectimport uniffi.aliasvault_core.KeyChainException+import uniffi.aliasvault_core.KeyChainKeysimport uniffi.aliasvault_core.mobileLoginEncryptAccountKey as rustMobileLoginEncryptAccountKey-import uniffi.aliasvault_core.openAccountKeyChain as rustOpenAccountKeyChain+import uniffi.aliasvault_core.openKeyChainWithAccountKey as rustOpenKeyChainWithAccountKey+import uniffi.aliasvault_core.openKeyChainWithUnlockKey as rustOpenKeyChainWithUnlockKeyimport uniffi.aliasvault_core.vaultBlobDecrypt as rustVaultBlobDecryptimport uniffi.aliasvault_core.vaultBlobEncrypt as rustVaultBlobEncrypt@@ -49,13 +51,15 @@ class VaultCrypto(get() = sessionKeys()?.accountKey?.let { Base64.encodeToString(it, Base64.NO_WRAP) }/**- * What the Account Key opens in the cached account key chain; a legacy key converts (see [LegacyKeyConversion]).+ * What the session key opens in the cached account key chain. A session opened before the device had a chain holds+ * the unlock key; once a sync caches the chain it opens as such and the Account Key replaces it (see [LegacyKeyConversion]).*/@Suppress("SwallowedException")private fun sessionKeys(): SessionKeys? {val key = accountKey ?: return nullreturn try {- openAccountKeyChain(key).also { if (!it.accountKey.contentEquals(key)) accountKey = it.accountKey }+ // This legacy key conversion call can be removed once all clients have updated to 0.31.0+.+ LegacyKeyConversion.openStoredKey(this, key).also { if (!it.accountKey.contentEquals(key)) accountKey = it.accountKey }} catch (e: Exception) {null}@@ -83,17 +87,30 @@ class VaultCrypto(// region Encryption Key Management/**- * Open a session with the unlock key or the Account Key and optionally persist the Account Key to keystore if- * biometrics are enabled.- *- * During login, if biometrics are enabled, this will attempt to persist the key to keystore.- * However, if Activity context is not available (common during login before UI is fully ready),- * the key will only be stored in memory. It will be persisted to keystore on next unlock- * when Activity context is available.+ * Open a session with the Account Key a device unlock method restored and persist it to the keystore if biometrics+ * are enabled.*/fun storeAccountKey(base64Key: String, authMethods: String) {- openSession(Base64.decode(base64Key, Base64.NO_WRAP))+ storeAccountKeyInMemory(base64Key)+ persistAccountKeyIfBiometricsEnabled(authMethods)+ }++ /**+ * Open a session with the unlock key of a password login; the session keeps the Account Key the chain yields and,+ * when asked, persists it to the keystore if biometrics are enabled.+ */+ fun openSessionWithUnlockKey(base64Key: String, persistToKeystore: Boolean, authMethods: String) {+ accountKey = openKeyChainWithUnlockKey(Base64.decode(base64Key, Base64.NO_WRAP)).accountKey+ if (persistToKeystore) {+ persistAccountKeyIfBiometricsEnabled(authMethods)+ }+ }+ /**+ * Persist the session's Account Key to the biometric keystore when biometrics are enabled. Without an Activity+ * context (common during login before the UI is ready) the key stays in memory and is persisted on the next unlock.+ */+ private fun persistAccountKeyIfBiometricsEnabled(authMethods: String) {if (authMethods.contains(BIOMETRICS_AUTH_METHOD)) {try {val latch = java.util.concurrent.CountDownLatch(1)@@ -130,10 +147,19 @@ class VaultCrypto(}/**- * Open a session in memory only with the unlock key or the Account Key.+ * Open a session in memory only with the Account Key a device unlock method restored.*/fun storeAccountKeyInMemory(base64Key: String) {- openSession(Base64.decode(base64Key, Base64.NO_WRAP))+ accountKey = openKeyChainWithAccountKey(Base64.decode(base64Key, Base64.NO_WRAP)).accountKey+ }++ /**+ * Open a session in memory with a key the keystore stored: the Account Key, or the unlock key of a store written+ * before the account had a key chain (see [LegacyKeyConversion]).+ */+ fun openSessionWithStoredKey(key: ByteArray) {+ // This legacy key conversion call can be removed once all clients have updated to 0.31.0+.+ accountKey = LegacyKeyConversion.openStoredKey(this, key).accountKey}/**@@ -184,34 +210,55 @@ class VaultCrypto(class SessionKeys(val vaultEncryptionKey: ByteArray, val accountPrivateKey: String?, val accountKey: ByteArray)/**- * Open the cached account key chain with the Account Key or the unlock key (Rust `openAccountKeyChain`).+ * The cached account key chain as the server sent it. [encryptedAccountPrivateKey] is null when the account has no+ * keypair; a private key that does not open must not fail the unlock, grants then stay closed.+ */+ private class CachedKeyChain(val encryptedAccountKey: String, val encryptedVek: String, val encryptedAccountPrivateKey: String?)++ /**+ * The cached account key chain, null for an account without one (its key is the vault key).*/- fun openAccountKeyChain(key: ByteArray): SessionKeys {- val chainJson = getAccountKeyChain() ?: return SessionKeys(key, null, key)- val chain = JSONObject(chainJson)- val encryptedAccountKey = chain.optString("encryptedAccountKey").takeIf { it.isNotEmpty() } ?: return SessionKeys(key, null, key)+ private fun cachedKeyChain(): CachedKeyChain? {+ val chain = JSONObject(getAccountKeyChain() ?: return null)+ val encryptedAccountKey = chain.optString("encryptedAccountKey").takeIf { it.isNotEmpty() } ?: return nullval encryptedVek = chain.optString("encryptedVek").takeIf { it.isNotEmpty() } ?: error("Account key chain is missing the encrypted VEK")- // A private key that does not open must not fail the unlock; grants stay closed until the next login.- val encryptedPrivateKey = chain.optString("encryptedAccountPrivateKey").takeIf { it.isNotEmpty() }+ return CachedKeyChain(encryptedAccountKey, encryptedVek, chain.optString("encryptedAccountPrivateKey").takeIf { it.isNotEmpty() })+ }++ /**+ * Open the cached account key chain with the unlock key of a password login (Rust `openKeyChainWithUnlockKey`).+ * Other platform implementations: VaultStore.openKeyChainWithUnlockKey (iOS), VaultKeyService.openKeyChain (core/client).+ */+ fun openKeyChainWithUnlockKey(unlockKey: ByteArray): SessionKeys = openKeyChain(unlockKey) { chain ->+ rustOpenKeyChainWithUnlockKey(unlockKey, chain.encryptedAccountKey, chain.encryptedVek, chain.encryptedAccountPrivateKey)+ }++ /**+ * Open the cached account key chain with the Account Key (Rust `openKeyChainWithAccountKey`).+ * Other platform implementations: VaultStore.openKeyChainWithAccountKey (iOS), VaultKeyService.openKeyChain (core/client).+ */+ fun openKeyChainWithAccountKey(accountKey: ByteArray): SessionKeys = openKeyChain(accountKey) { chain ->+ rustOpenKeyChainWithAccountKey(accountKey, chain.encryptedVek, chain.encryptedAccountPrivateKey)+ }+ /**+ * Open the cached chain through [open]; without a chain [key] is the vault key. Either rejection is E-206, an+ * unreadable chain E-207 (the Account Key opened, so never a wrong password).+ */+ private fun openKeyChain(key: ByteArray, open: (CachedKeyChain) -> KeyChainKeys): SessionKeys {+ val chain = cachedKeyChain() ?: return SessionKeys(key, null, key)val keys = try {- rustOpenAccountKeyChain(key, encryptedAccountKey, encryptedVek, encryptedPrivateKey)+ open(chain)} catch (e: KeyChainException.UnlockKeyRejected) {throw AppError.UnlockKeyRejected(cause = e)+ } catch (e: KeyChainException.AccountKeyRejected) {+ throw AppError.UnlockKeyRejected(cause = e)} catch (e: KeyChainException.KeyChainUnreadable) {- // The account key opened, so this is a damaged chain and never a wrong password.throw AppError.KeyChainUnreadable(e.message ?: "decrypt failed", e)}return SessionKeys(keys.vaultEncryptionKey, keys.accountPrivateKey, keys.accountKey)}- /**- * Open a session with a key that opens the cached account key chain; the session keeps the Account Key it yields.- */- fun openSession(key: ByteArray) {- accountKey = openAccountKeyChain(key).accountKey- }-/*** Check if biometric authentication is enabled and available.*/@@ -249,7 +296,8 @@ class VaultCrypto(override fun onSuccess(result: String) {try {val keystoreKey = Base64.decode(result, Base64.NO_WRAP)- openSession(keystoreKey)+ openSessionWithStoredKey(keystoreKey)+ // This legacy key conversion call can be removed once all clients have updated to 0.31.0+.accountKey?.let { LegacyKeyConversion.convertLegacyKeystoreKey(keystoreProvider, keystoreKey, it) }callback.onSuccess(Base64.encodeToString(key(), Base64.NO_WRAP))} catch (e: AppError) {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 5e0b455de..dfdc8e80c 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@@ -178,7 +178,7 @@ class VaultStore(// region Crypto Methods/**- * Open a session with the unlock key or the Account Key and persist the Account Key to keystore if biometrics+ * Open a session with the Account Key a device unlock method restored and persist it to the keystore if biometrics* are enabled.*/fun storeAccountKey(base64Key: String) {@@ -186,12 +186,27 @@ class VaultStore(}/**- * Open a session in memory only with the unlock key or the Account Key.+ * Open a session in memory only with the Account Key a device unlock method restored.*/fun storeAccountKeyInMemory(base64Key: String) {crypto.storeAccountKeyInMemory(base64Key)}+ /**+ * Open a session with the unlock key of a password login; with [persistToKeystore] the Account Key the chain yields+ * is also stored for biometric unlock.+ */+ fun openSessionWithUnlockKey(unlockKeyBase64: String, persistToKeystore: Boolean) {+ crypto.openSessionWithUnlockKey(unlockKeyBase64, persistToKeystore, auth.getAuthMethods())+ }++ /**+ * Open a session in memory with a key the biometric keystore stored (see [LegacyKeyConversion]).+ */+ fun openSessionWithStoredKey(base64Key: String) {+ crypto.openSessionWithStoredKey(android.util.Base64.decode(base64Key, android.util.Base64.NO_WRAP))+ }+/*** Clear the encryption key from memory.* This forces getEncryptionKey() to fetch from keystore on next biometric access.@@ -331,7 +346,7 @@ class VaultStore(// Derive the unlock key from the password and open the chain; a wrong password fails to open it.val derivedKey = crypto.deriveKeyFromPassword(password, salt, encryptionType, encryptionSettings)- crypto.openAccountKeyChain(derivedKey)+ crypto.openKeyChainWithUnlockKey(derivedKey)android.util.Base64.encodeToString(derivedKey, android.util.Base64.NO_WRAP)} catch (e: Exception) {// Password incorrect or the key chain did not open - intentionally return null@@ -973,7 +988,8 @@ class VaultStore(val key = pin.unlockWithPin(pinValue)markSuccessfulAuth()- val accountKey = crypto.openAccountKeyChain(android.util.Base64.decode(key, android.util.Base64.NO_WRAP)).accountKey+ // This legacy key conversion call can be removed once all clients have updated to 0.31.0+.+ val accountKey = LegacyKeyConversion.openStoredKey(crypto, android.util.Base64.decode(key, android.util.Base64.NO_WRAP)).accountKeyval accountKeyBase64 = android.util.Base64.encodeToString(accountKey, android.util.Base64.NO_WRAP)LegacyKeyConversion.convertLegacyPinKey(pin, pinValue, key, accountKeyBase64)return accountKeyBase64diff --git a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultSync.kt b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultSync.ktindex c7ccd2160..0d65ffb79 100644--- a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultSync.kt+++ b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultSync.kt@@ -120,7 +120,7 @@ class VaultSync(if (!result.optBoolean("success", false)) {throw syncError(result)}- vaultStore.storeAccountKey(derivedKeyBase64)+ vaultStore.openSessionWithUnlockKey(derivedKeyBase64, persistToKeystore = true)vaultStore.encryptionKey}diff --git a/apps/mobile-app/context/DbContext.tsx b/apps/mobile-app/context/DbContext.tsxindex e4a547e81..3689d3afd 100644--- a/apps/mobile-app/context/DbContext.tsx+++ b/apps/mobile-app/context/DbContext.tsx@@ -31,7 +31,7 @@ type DbContextType = {*/shouldSuppressEmailErrors: () => boolean;refreshSyncState: () => Promise<void>;- storeAccountKey: (derivedKey: string) => Promise<void>;+ openSessionWithUnlockKey: (unlockKey: string) => Promise<void>;storeUnlockKeyDerivationParams: (keyDerivationParams: UnlockKeyDerivationParams) => Promise<void>;requiresLegacySqliteBlobMigration: () => Promise<boolean>;hasPendingMigrations: () => Promise<boolean>;@@ -111,13 +111,13 @@ export const DbProvider: React.FC<{ children: React.ReactNode }> = ({ children }}, []);/**- * Open a session from the unlock key (the password's Argon2id output) in the native module, in memory and optionally- * keychain. The session keeps the Account Key the account key chain resolves.+ * Open a session from the unlock key (the password's Argon2id output) in the native module, in memory and in the+ * keychain when biometrics are enabled. The session keeps the Account Key the account key chain yields.*- * @param derivedKey The password-derived unlock key+ * @param unlockKey The password-derived unlock key*/- const storeAccountKey = useCallback(async (derivedKey: string) => {- await sqliteClient.storeAccountKey(derivedKey);+ const openSessionWithUnlockKey = useCallback(async (unlockKey: string) => {+ await sqliteClient.openSessionWithUnlockKey(unlockKey, true);}, [sqliteClient]);/**@@ -266,7 +266,7 @@ export const DbProvider: React.FC<{ children: React.ReactNode }> = ({ children }* @throws Error with error code if unlock fails - caller should handle the error*/const testDatabaseConnection = useCallback(async (derivedKey: string, persistToKeychain = true): Promise<boolean> => {- await sqliteClient.storeAccountKeyInMemory(derivedKey);+ await sqliteClient.openSessionWithUnlockKey(derivedKey, false);await unlockVault();@@ -280,7 +280,7 @@ export const DbProvider: React.FC<{ children: React.ReactNode }> = ({ children }* The old key in keychain is preserved for future biometric unlocks.*/if (persistToKeychain) {- await sqliteClient.storeAccountKey(derivedKey);+ await sqliteClient.openSessionWithUnlockKey(derivedKey, true);}return true;}@@ -295,7 +295,7 @@ export const DbProvider: React.FC<{ children: React.ReactNode }> = ({ children }*/const verifyUnlockKey = useCallback(async (derivedKey: string): Promise<boolean> => {try {- await sqliteClient.storeAccountKeyInMemory(derivedKey);+ await sqliteClient.openSessionWithUnlockKey(derivedKey, false);await unlockVault();const version = await sqliteClient.getDatabaseVersion();@@ -329,11 +329,11 @@ export const DbProvider: React.FC<{ children: React.ReactNode }> = ({ children }testDatabaseConnection,verifyUnlockKey,unlockVault,- storeAccountKey,+ openSessionWithUnlockKey,storeUnlockKeyDerivationParams,checkStoredVault,setDatabaseAvailable,- }), [sqliteClient, dbInitialized, dbAvailable, isDirty, dirtyScopes, isSyncing, isUploading, isOffline, setIsSyncing, setIsUploading, setIsOffline, shouldSuppressEmailErrors, refreshSyncState, requiresLegacySqliteBlobMigration, hasPendingMigrations, clearDatabase, getVaultMetadata, testDatabaseConnection, verifyUnlockKey, unlockVault, storeAccountKey, storeUnlockKeyDerivationParams, checkStoredVault, setDatabaseAvailable]);+ }), [sqliteClient, dbInitialized, dbAvailable, isDirty, dirtyScopes, isSyncing, isUploading, isOffline, setIsSyncing, setIsUploading, setIsOffline, shouldSuppressEmailErrors, refreshSyncState, requiresLegacySqliteBlobMigration, hasPendingMigrations, clearDatabase, getVaultMetadata, testDatabaseConnection, verifyUnlockKey, unlockVault, openSessionWithUnlockKey, storeUnlockKeyDerivationParams, checkStoredVault, setDatabaseAvailable]);return (<DbContext.Provider value={contextValue}>diff --git a/apps/mobile-app/ios/NativeVaultManager/NativeVaultManager.swift b/apps/mobile-app/ios/NativeVaultManager/NativeVaultManager.swiftindex b27296fa7..57c9c2339 100644--- a/apps/mobile-app/ios/NativeVaultManager/NativeVaultManager.swift+++ b/apps/mobile-app/ios/NativeVaultManager/NativeVaultManager.swift@@ -63,30 +63,18 @@ public class NativeVaultManager: NSObject {}}- /// Open a session in memory with the unlock key or the Account Key, without keychain persistence.- /// Use this to test if a key is valid before persisting.+ /// Open a session with the unlock key of a password login; with `persistToKeychain` the Account Key it yields is also+ /// stored in the keychain if Face ID is enabled.@objc- func storeAccountKeyInMemory(_ base64Key: String,- resolver resolve: @escaping RCTPromiseResolveBlock,- rejecter reject: @escaping RCTPromiseRejectBlock) {- do {- try vaultStore.storeAccountKeyInMemory(base64Key: base64Key)- resolve(nil)- } catch {- reject("ERR_STORE_KEY_MEMORY", "Failed to store Account Key in memory: \(error.localizedDescription)", error)- }- }-- /// Open a session with the unlock key or the Account Key AND persist the Account Key to keychain if Face ID is enabled.- @objc- func storeAccountKey(_ base64Key: String,- resolver resolve: @escaping RCTPromiseResolveBlock,- rejecter reject: @escaping RCTPromiseRejectBlock) {+ func openSessionWithUnlockKey(_ unlockKeyBase64: String,+ persistToKeychain: Bool,+ resolver resolve: @escaping RCTPromiseResolveBlock,+ rejecter reject: @escaping RCTPromiseRejectBlock) {do {- try vaultStore.storeAccountKey(base64Key: base64Key)+ try vaultStore.openSessionWithUnlockKey(base64Key: unlockKeyBase64, persistToKeychain: persistToKeychain)resolve(nil)} catch {- reject("KEYCHAIN_ERROR", "Failed to store Account Key: \(error.localizedDescription)", error)+ reject("ERR_OPEN_SESSION", "Failed to open the session with the unlock key: \(error.localizedDescription)", error)}}@@ -1064,7 +1052,7 @@ public class NativeVaultManager: NSObject {}// Open the session in memory only- try self.vaultStore.storeAccountKeyInMemory(base64Key: unlockKeyBase64)+ try self.vaultStore.openSessionWithUnlockKey(base64Key: unlockKeyBase64, persistToKeychain: false)// Unlock the vaulttry self.vaultStore.unlockVault()@@ -1409,7 +1397,7 @@ public class NativeVaultManager: NSObject {throw NSError(domain: "NativeVaultManager", code: -1, userInfo: [NSLocalizedDescriptionKey: "Incorrect password"])}- try self.vaultStore.storeAccountKeyInMemory(base64Key: unlockKeyBase64)+ try self.vaultStore.openSessionWithUnlockKey(base64Key: unlockKeyBase64, persistToKeychain: false)// Success - dismiss and resolveawait MainActor.run {@@ -1585,9 +1573,10 @@ private enum RustCoreDispatcher {case "argon2DeriveKey":return try json(bytes: try RustCoreFramework.argon2DeriveKey(password: try args.string(0), salt: try args.string(1), encryptionSettings: try args.string(2)))case "deriveSrpPasswordHash": return try json(try RustCoreFramework.deriveSrpPasswordHash(unlockKey: try args.data(0), encryptionType: try args.string(1)))- case "openAccountKeyChain":- let key = try args.data(0)- return try openKeyChain(key: key, encryptedAccountKey: try args.string(1), encryptedVek: try args.string(2), encryptedAccountPrivateKey: args.optionalString(3))+ case "openKeyChainWithUnlockKey":+ return try keyChainResult { try RustCoreFramework.openKeyChainWithUnlockKey(unlockKey: try args.data(0), encryptedAccountKey: try args.string(1), encryptedVek: try args.string(2), encryptedAccountPrivateKey: args.optionalString(3)) }+ case "openKeyChainWithAccountKey":+ return try keyChainResult { try RustCoreFramework.openKeyChainWithAccountKey(accountKey: try args.data(0), encryptedVek: try args.string(1), encryptedAccountPrivateKey: args.optionalString(2)) }case "createAccountKeyHierarchyJson":return try RustCoreFramework.createAccountKeyHierarchyJson(unlockKey: try args.data(0), publicKeyJwk: try args.string(1), privateKeyJwk: try args.string(2))case "reencryptAccountKeyJson":@@ -1626,12 +1615,10 @@ private enum RustCoreDispatcher {return text}- /// Open a key chain and report the outcome as the `KeyChainOpenResult` JSON the client core expects.- private static func openKeyChain(key: Data, encryptedAccountKey: String, encryptedVek: String, encryptedAccountPrivateKey: String?) throws -> String {+ /// Open a key chain through `open` and report the outcome as the `KeyChainOpenResult` JSON the client core expects.+ private static func keyChainResult(_ open: () throws -> KeyChainKeys) throws -> String {do {- let keys = try RustCoreFramework.openAccountKeyChain(- storedKey: key, encryptedAccountKey: encryptedAccountKey, encryptedVek: encryptedVek, encryptedAccountPrivateKey: encryptedAccountPrivateKey- )+ let keys = try open()return try json(["status": "opened","vaultEncryptionKey": keys.vaultEncryptionKey.base64EncodedString(),@@ -1640,6 +1627,8 @@ private enum RustCoreDispatcher {])} catch KeyChainError.UnlockKeyRejected {return try json(["status": "unlockKeyRejected"])+ } catch KeyChainError.AccountKeyRejected {+ return try json(["status": "accountKeyRejected"])} catch KeyChainError.KeyChainUnreadable(let message) {return try json(["status": "keyChainUnreadable", "message": message])}diff --git a/apps/mobile-app/ios/NativeVaultManager/RCTNativeVaultManager.mm b/apps/mobile-app/ios/NativeVaultManager/RCTNativeVaultManager.mmindex c86b5a6d4..7188c407f 100644--- a/apps/mobile-app/ios/NativeVaultManager/RCTNativeVaultManager.mm+++ b/apps/mobile-app/ios/NativeVaultManager/RCTNativeVaultManager.mm@@ -97,12 +97,8 @@[vaultManager storeMetadata:metadata resolver:resolve rejecter:reject];}-- (void)storeAccountKeyInMemory:(NSString *)base64Key resolve:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject {- [vaultManager storeAccountKeyInMemory:base64Key resolver:resolve rejecter:reject];-}--- (void)storeAccountKey:(NSString *)base64Key resolve:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject {- [vaultManager storeAccountKey:base64Key resolver:resolve rejecter:reject];+- (void)openSessionWithUnlockKey:(NSString *)unlockKeyBase64 persistToKeychain:(BOOL)persistToKeychain resolve:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject {+ [vaultManager openSessionWithUnlockKey:unlockKeyBase64 persistToKeychain:persistToKeychain resolver:resolve rejecter:reject];}- (void)clearEncryptionKeyFromMemory:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject {diff --git a/apps/mobile-app/ios/VaultStoreKit/Services/VaultSync.swift b/apps/mobile-app/ios/VaultStoreKit/Services/VaultSync.swiftindex 002f7eb88..166441359 100644--- a/apps/mobile-app/ios/VaultStoreKit/Services/VaultSync.swift+++ b/apps/mobile-app/ios/VaultStoreKit/Services/VaultSync.swift@@ -79,7 +79,7 @@ internal final class VaultSync {guard result["success"] as? Bool == true else {throw Self.syncError(from: result)}- try vaultStore.storeAccountKey(base64Key: derivedKeyBase64)+ try vaultStore.openSessionWithUnlockKey(base64Key: derivedKeyBase64, persistToKeychain: true)_ = try vaultStore.getEncryptionKey()}diff --git a/apps/mobile-app/ios/VaultStoreKit/VaultStore+Crypto.swift b/apps/mobile-app/ios/VaultStoreKit/VaultStore+Crypto.swiftindex 52893a29c..795683be5 100644--- a/apps/mobile-app/ios/VaultStoreKit/VaultStore+Crypto.swift+++ b/apps/mobile-app/ios/VaultStoreKit/VaultStore+Crypto.swift@@ -23,15 +23,30 @@ extension VaultStore {return derivedKey}- /// Open a session in memory with the unlock key or the Account Key, without keychain persistence.- /// Use this to test if a key is valid before persisting.+ /// Open a session in memory with the Account Key a device unlock method restored, without keychain persistence.public func storeAccountKeyInMemory(base64Key: String) throws {+ self.accountKey = try openKeyChainWithAccountKey(try keyData(base64Key)).accountKey+ print("Opened session in memory only (no keychain persistence)")+ }++ /// Open a session with the unlock key of a password login; the session keeps the Account Key the chain yields and,+ /// when asked, persists it to the keychain if Face ID is enabled.+ public func openSessionWithUnlockKey(base64Key: String, persistToKeychain: Bool) throws {+ self.accountKey = try openKeyChainWithUnlockKey(try keyData(base64Key)).accountKey+ if persistToKeychain {+ try persistAccountKeyIfBiometricsEnabled()+ }+ }++ /// The 32 bytes of a base64 key.+ private func keyData(_ base64Key: String) throws -> Data {guard let keyData = Data(base64Encoded: base64Key) else {throw NSError(domain: "VaultStore", code: 6, userInfo: [NSLocalizedDescriptionKey: "Invalid base64 key"])}-- try openSession(with: keyData)- print("Opened session in memory only (no keychain persistence)")+ guard keyData.count == 32 else {+ throw NSError(domain: "VaultStore", code: 7, userInfo: [NSLocalizedDescriptionKey: "Invalid key length. Expected 32 bytes"])+ }+ return keyData}/// Clear the Account Key from memory.@@ -42,12 +57,14 @@ extension VaultStore {print("Cleared Account Key from memory")}- /// Open a session in memory with the unlock key or the Account Key AND persist the Account Key to keychain if Face ID is enabled.+ /// Open a session with the Account Key a device unlock method restored AND persist it to the keychain if Face ID is enabled.public func storeAccountKey(base64Key: String) throws {- // First open the session in memorytry storeAccountKeyInMemory(base64Key: base64Key)+ try persistAccountKeyIfBiometricsEnabled()+ }- // Then persist to keychain if Face ID is enabled AND keystore is available+ /// Persist the session's Account Key to the keychain when Face ID is enabled and the keystore is available.+ private func persistAccountKeyIfBiometricsEnabled() throws {if self.enabledAuthMethods.contains(.faceID), let keyData = self.accountKey {if isKeystoreAvailable() {try storeKeyInKeychain(keyData)@@ -60,15 +77,6 @@ extension VaultStore {}}- /// Open a session with a key that opens the cached account key chain; the session keeps the Account Key it yields.- internal func openSession(with key: Data) throws {- guard key.count == 32 else {- throw NSError(domain: "VaultStore", code: 7, userInfo: [NSLocalizedDescriptionKey: "Invalid key length. Expected 32 bytes"])- }-- self.accountKey = try openAccountKeyChain(with: key).accountKey- }-/// Store the key derivation parameters used for deriving the encryption key from the plain text passwordpublic func storeUnlockKeyDerivationParams(_ keyDerivationParams: String) throws {// Store the key derivation params in memory@@ -110,30 +118,57 @@ extension VaultStore {let accountKey: Data}- /// Open the cached account key chain with the Account Key or the unlock key (Rust `openAccountKeyChain`).- internal func openAccountKeyChain(with key: Data) throws -> SessionKeys {+ /// The cached account key chain as the server sent it.+ private struct CachedKeyChain {+ let encryptedAccountKey: String+ let encryptedVek: String+ /// Nil when the account has no keypair; a private key that does not open must not fail the unlock, grants then stay closed.+ let encryptedAccountPrivateKey: String?+ }++ /// The cached account key chain, nil for an account without one (its key is the vault key).+ private func cachedKeyChain() throws -> CachedKeyChain? {guard let chainJson = getAccountKeyChain(),let chainData = chainJson.data(using: .utf8),let chain = try? JSONSerialization.jsonObject(with: chainData) as? [String: Any],let encryptedAccountKey = chain["encryptedAccountKey"] as? String, !encryptedAccountKey.isEmpty else {- return SessionKeys(vaultEncryptionKey: key, accountPrivateKey: nil, accountKey: key)+ return nil}-guard let encryptedVek = chain["encryptedVek"] as? String, !encryptedVek.isEmpty else {throw NSError(domain: "VaultStore", code: 41, userInfo: [NSLocalizedDescriptionKey: "Account key chain is missing the encrypted VEK"])}-- // A private key that does not open must not fail the unlock; grants stay closed until the next login.let encryptedPrivateKey = (chain["encryptedAccountPrivateKey"] as? String).flatMap { $0.isEmpty ? nil : $0 }+ return CachedKeyChain(encryptedAccountKey: encryptedAccountKey, encryptedVek: encryptedVek, encryptedAccountPrivateKey: encryptedPrivateKey)+ }++ /// Open the cached account key chain with the unlock key of a password login (Rust `openKeyChainWithUnlockKey`).+ /// Other platform implementations: VaultCrypto.openKeyChainWithUnlockKey (Android), VaultKeyService.openKeyChain (core/client).+ internal func openKeyChainWithUnlockKey(_ unlockKey: Data) throws -> SessionKeys {+ return try openKeyChain(unlockKey) { chain in+ try RustCoreFramework.openKeyChainWithUnlockKey(unlockKey: unlockKey, encryptedAccountKey: chain.encryptedAccountKey, encryptedVek: chain.encryptedVek, encryptedAccountPrivateKey: chain.encryptedAccountPrivateKey)+ }+ }++ /// Open the cached account key chain with the Account Key (Rust `openKeyChainWithAccountKey`).+ /// Other platform implementations: VaultCrypto.openKeyChainWithAccountKey (Android), VaultKeyService.openKeyChain (core/client).+ internal func openKeyChainWithAccountKey(_ accountKey: Data) throws -> SessionKeys {+ return try openKeyChain(accountKey) { chain in+ try RustCoreFramework.openKeyChainWithAccountKey(accountKey: accountKey, encryptedVek: chain.encryptedVek, encryptedAccountPrivateKey: chain.encryptedAccountPrivateKey)+ }+ }++ /// Open the cached chain through `open`; without a chain `key` is the vault key. Either rejection is E-206, an+ /// unreadable chain E-207 (the Account Key opened, so never a wrong password).+ private func openKeyChain(_ key: Data, _ open: (CachedKeyChain) throws -> KeyChainKeys) throws -> SessionKeys {+ guard let chain = try cachedKeyChain() else {+ return SessionKeys(vaultEncryptionKey: key, accountPrivateKey: nil, accountKey: key)+ }do {- let keys = try RustCoreFramework.openAccountKeyChain(- storedKey: key, encryptedAccountKey: encryptedAccountKey, encryptedVek: encryptedVek, encryptedAccountPrivateKey: encryptedPrivateKey- )+ let keys = try open(chain)return SessionKeys(vaultEncryptionKey: keys.vaultEncryptionKey, accountPrivateKey: keys.accountPrivateKey, accountKey: keys.accountKey)- } catch KeyChainError.UnlockKeyRejected {+ } catch KeyChainError.UnlockKeyRejected, KeyChainError.AccountKeyRejected {throw AppError.unlockKeyRejected} catch KeyChainError.KeyChainUnreadable(let message) {- // The account key opened, so this is a damaged chain and never a wrong password.throw AppError.keyChainUnreadable(message: message)}}@@ -174,7 +209,7 @@ extension VaultStore {// Derive the unlock key from the password and unwrap the chain; a wrong password fails the unwrap.let derivedKey = try deriveKeyFromPassword(password, salt: salt, encryptionType: encryptionType, encryptionSettings: encryptionSettings)- _ = try openAccountKeyChain(with: derivedKey)+ _ = try openKeyChainWithUnlockKey(derivedKey)return derivedKey.base64EncodedString()} catch {// Password incorrect or the key chain did not open@@ -252,7 +287,8 @@ extension VaultStore {/// Get the encryption key - the key used to encrypt and decrypt the vault.internal func getEncryptionKey() throws -> Data {let key = try getAccountKey()- let keys = try openAccountKeyChain(with: key)+ // This legacy key conversion call can be removed once all clients have updated to 0.31.0+.+ let keys = try openStoredKey(key)if keys.accountKey != key {// A legacy key, see `VaultStore+LegacyKeyConversion`.self.accountKey = keys.accountKey@@ -315,10 +351,10 @@ extension VaultStore {}do {- try openSession(with: keyData)- if let accountKey = self.accountKey {- convertLegacyKeychainKey(keychainKey: keyData, accountKey: accountKey)- }+ // This legacy key conversion call can be removed once all clients have updated to 0.31.0+.+ let accountKey = try openStoredKey(keyData).accountKey+ self.accountKey = accountKey+ convertLegacyKeychainKey(keychainKey: keyData, accountKey: accountKey)} catch let vaultError as AppError {print("The Account Key from the keychain does not open the account key chain: \(vaultError.message)")throw vaultErrordiff --git a/apps/mobile-app/ios/VaultStoreKit/VaultStore+LegacyKeyConversion.swift b/apps/mobile-app/ios/VaultStoreKit/VaultStore+LegacyKeyConversion.swiftindex eda78e566..5cf9989e5 100644--- a/apps/mobile-app/ios/VaultStoreKit/VaultStore+LegacyKeyConversion.swift+++ b/apps/mobile-app/ios/VaultStoreKit/VaultStore+LegacyKeyConversion.swift@@ -4,11 +4,25 @@ import Foundation////// The keychain and the PIN protect the Account Key, the one secret an unlocked session holds. Before 0.31.0 they/// protected the unlock key (the Argon2id output of the master password). A key stored then (a 0.30.x install, or an-/// account upgraded on another device) still opens the account key chain, which yields the Account Key; these helpers-/// then store the Account Key in its place, once. For an account without a key chain the stored key is the vault key.+/// account upgraded on another device) still opens the account key chain, as an unlock key; these helpers then store the+/// Account Key in its place, once. For an account without a key chain the stored key is the vault key.///-/// TODO: remove once accounts without a key chain (pre-0.31.0) are no longer supported.+/// Other platform implementations: LegacyKeyConversion.kt (Android), LegacyKeyConversion.ts (core/client and browser extension).+///+/// TODO: remove once accounts without a key chain (pre-0.31.0) are no longer supported; `openStoredKey` then becomes+/// `openKeyChainWithAccountKey`.extension VaultStore {+ /// Open the cached account key chain with a key the keychain, the PIN or the session stored: the Account Key, or+ /// the unlock key a store written before the account had a key chain holds.+ internal func openStoredKey(_ key: Data) throws -> SessionKeys {+ do {+ return try openKeyChainWithAccountKey(key)+ } catch AppError.unlockKeyRejected {+ // LEGACY: the stored key is an unlock key; the caller stores the Account Key the chain yields in its place.+ return try openKeyChainWithUnlockKey(key)+ }+ }+/// Re-encrypt the PIN with the Account Key when it still protected an unlock key.internal func convertLegacyPinKey(pin: String, pinKey: Data, accountKey: Data) {guard accountKey != pinKey else { return }diff --git a/apps/mobile-app/ios/VaultStoreKit/VaultStore+Pin.swift b/apps/mobile-app/ios/VaultStoreKit/VaultStore+Pin.swiftindex 0c6955ed3..1fde3209a 100644--- a/apps/mobile-app/ios/VaultStoreKit/VaultStore+Pin.swift+++ b/apps/mobile-app/ios/VaultStoreKit/VaultStore+Pin.swift@@ -82,7 +82,8 @@ extension VaultStore {/// - Throws: PinUnlockError with specific error type and metadatapublic func unlockWithPin(_ pin: String) throws -> String {let pinProtectedKey = try decryptPinProtectedKey(pin)- let accountKey = try openAccountKeyChain(with: pinProtectedKey).accountKey+ // This legacy key conversion call can be removed once all clients have updated to 0.31.0+.+ let accountKey = try openStoredKey(pinProtectedKey).accountKeyconvertLegacyPinKey(pin: pin, pinKey: pinProtectedKey, accountKey: accountKey)return accountKey.base64EncodedString()}diff --git a/apps/mobile-app/ios/VaultStoreKit/VaultStore.swift b/apps/mobile-app/ios/VaultStoreKit/VaultStore.swiftindex e5db72a98..a92a4bb12 100644--- a/apps/mobile-app/ios/VaultStoreKit/VaultStore.swift+++ b/apps/mobile-app/ios/VaultStoreKit/VaultStore.swift@@ -52,12 +52,14 @@ public class VaultStore {return sessionKeys?.accountKey.base64EncodedString()}- /// What the Account Key opens in the cached account key chain.+ /// What the session key opens in the cached account key chain. A session opened before the device had a chain holds the+ /// unlock key, which still opens it as such once a sync caches the chain (see `VaultStore+LegacyKeyConversion`).private var sessionKeys: SessionKeys? {guard let accountKey = accountKey else {return nil}- return try? openAccountKeyChain(with: accountKey)+ // This legacy key conversion call can be removed once all clients have updated to 0.31.0+.+ return try? openStoredKey(accountKey)}/// Last successful biometric/PIN auth operation.diff --git a/apps/mobile-app/platform/NativeRustCore.ts b/apps/mobile-app/platform/NativeRustCore.tsindex cbc52700f..d7adc3177 100644--- a/apps/mobile-app/platform/NativeRustCore.ts+++ b/apps/mobile-app/platform/NativeRustCore.ts@@ -84,7 +84,8 @@ export const nativeRustCore: IRustCore = {argon2DeriveKey: (password, salt, encryptionSettings) => callForBytes('argon2DeriveKey', password, salt, encryptionSettings),deriveSrpPasswordHash: (unlockKeyBase64, encryptionType) => call('deriveSrpPasswordHash', unlockKeyBase64, encryptionType),- openAccountKeyChain: (storedKey, encryptedAccountKey, encryptedVek, encryptedAccountPrivateKey) => call('openAccountKeyChain', storedKey, encryptedAccountKey, encryptedVek, encryptedAccountPrivateKey),+ openKeyChainWithUnlockKey: (unlockKey, encryptedAccountKey, encryptedVek, encryptedAccountPrivateKey) => call('openKeyChainWithUnlockKey', unlockKey, encryptedAccountKey, encryptedVek, encryptedAccountPrivateKey),+ openKeyChainWithAccountKey: (accountKey, encryptedVek, encryptedAccountPrivateKey) => call('openKeyChainWithAccountKey', accountKey, encryptedVek, encryptedAccountPrivateKey),createAccountKeyHierarchy: (unlockKeyBase64, publicKeyJwk, privateKeyJwk) => call('createAccountKeyHierarchyJson', unlockKeyBase64, publicKeyJwk, privateKeyJwk),reencryptAccountKey: (encryptedAccountKey, oldUnlockKeyBase64, newUnlockKeyBase64) => call('reencryptAccountKeyJson', encryptedAccountKey, oldUnlockKeyBase64, newUnlockKeyBase64),diff --git a/apps/mobile-app/specs/NativeVaultManager.ts b/apps/mobile-app/specs/NativeVaultManager.tsindex 0c56a9487..d5fa1f663 100644--- a/apps/mobile-app/specs/NativeVaultManager.ts+++ b/apps/mobile-app/specs/NativeVaultManager.ts@@ -63,9 +63,8 @@ export interface Spec extends TurboModule {// Database/encryption key operationsstoreMetadata(metadata: string): Promise<void>;setAuthMethods(authMethods: string[]): Promise<void>;- storeAccountKeyInMemory(base64Key: string): Promise<void>;+ openSessionWithUnlockKey(unlockKeyBase64: string, persistToKeychain: boolean): Promise<void>;clearEncryptionKeyFromMemory(): Promise<void>;- storeAccountKey(base64Key: string): Promise<void>;storeUnlockKeyDerivationParams(keyDerivationParams: string): Promise<void>;getUnlockKeyDerivationParams(): Promise<string | null>;getAccountKeyChain(): Promise<string | null>;diff --git a/apps/mobile-app/utils/SqliteClient.ts b/apps/mobile-app/utils/SqliteClient.tsindex b58361591..db39acdb1 100644--- a/apps/mobile-app/utils/SqliteClient.ts+++ b/apps/mobile-app/utils/SqliteClient.ts@@ -176,30 +176,17 @@ class SqliteClient {}/**- * Open a session in memory with the unlock key or the Account Key, without keychain persistence.- * Use this to test if a key is valid before persisting.+ * Open a session with the unlock key of a password login; the native session keeps the Account Key the key chain+ * yields. With `persistToKeychain` it is also stored for biometric unlock (may trigger a biometric prompt).*- * @param base64Key The base64 encoded unlock key or Account Key+ * @param unlockKeyBase64 The base64 encoded unlock key, the password's Argon2id output+ * @param persistToKeychain Whether to also persist the Account Key to the keychain or keystore*/- public async storeAccountKeyInMemory(base64Key: string): Promise<void> {+ public async openSessionWithUnlockKey(unlockKeyBase64: string, persistToKeychain: boolean): Promise<void> {try {- await NativeVaultManager.storeAccountKeyInMemory(base64Key);+ await NativeVaultManager.openSessionWithUnlockKey(unlockKeyBase64, persistToKeychain);} catch (error) {- console.error('Error storing Account Key in memory:', error);- throw error;- }- }-- /**- * Open a session with the unlock key or the Account Key AND persist the Account Key to keychain (may trigger biometric prompt).- *- * @param base64Key The base64 encoded unlock key or Account Key- */- public async storeAccountKey(base64Key: string): Promise<void> {- try {- await NativeVaultManager.storeAccountKey(base64Key);- } catch (error) {- console.error('Error storing Account Key:', error);+ console.error('Error opening the session with the unlock key:', error);throw error;}}diff --git a/apps/web/src/pages/auth/Login.tsx b/apps/web/src/pages/auth/Login.tsxindex 3314c4449..8b570521d 100644--- a/apps/web/src/pages/auth/Login.tsx+++ b/apps/web/src/pages/auth/Login.tsx@@ -119,7 +119,7 @@ const Login: React.FC = () => {await auth.setAuthTokens(normalizedUsername, accessToken, refreshToken);// Fetch the key chain, check the unlock key opens it and cache it; without a usable chain the session is useless, so end it.- await UnlockService.completeKeyChainLogin(unlockKey, params, webApi, () => auth.logout());+ await UnlockService.completeKeyChainLogin({ unlockKey }, params, webApi, () => auth.logout());if (loginPassword) {await UnlockService.upgradeKeyDerivation(loginPassword, params, unlockKey, webApi, normalizedUsername);}diff --git a/apps/web/src/pages/auth/Unlock.tsx b/apps/web/src/pages/auth/Unlock.tsxindex 62a346183..f1e704429 100644--- a/apps/web/src/pages/auth/Unlock.tsx+++ b/apps/web/src/pages/auth/Unlock.tsx@@ -200,7 +200,7 @@ const Unlock: React.FC = () => {await auth.setAuthTokens(result.username, result.token, result.refreshToken);// Throws an unlock-key-rejected (E-206) error if the key does not open the key chain.- await UnlockService.completeKeyChainLogin(result.accountKey, result, webApi);+ await UnlockService.completeKeyChainLogin({ accountKey: result.accountKey }, result, webApi);navigate('/sync', { replace: true });} catch (err) {console.error('Mobile unlock error:', err);diff --git a/apps/web/src/utils/WebAuthnService.ts b/apps/web/src/utils/WebAuthnService.tsindex c588e6a0f..3b763daf0 100644--- a/apps/web/src/utils/WebAuthnService.ts+++ b/apps/web/src/utils/WebAuthnService.ts@@ -163,7 +163,7 @@ export const WebAuthnService = {const derivedKey = await getCredentialDerivedKey(credentialId, salt);const accountKey = await rustCore().symmetricDecrypt(encrypted, derivedKey);try {- await VaultKeyService.verifyUnlockKey(accountKey);+ await VaultKeyService.verifyAccountKey(accountKey);} catch (error) {// A key the chain rejects is discarded, the password unlock still works.if (error instanceof Error && extractErrorCode(error.message) === AppErrorCode.UNLOCK_KEY_REJECTED) {diff --git a/core/client/src/auth/MasterPasswordService.ts b/core/client/src/auth/MasterPasswordService.tsindex 48475c45d..fc6b6634f 100644--- a/core/client/src/auth/MasterPasswordService.ts+++ b/core/client/src/auth/MasterPasswordService.ts@@ -243,7 +243,7 @@ export class MasterPasswordService {}try {- await VaultKeyService.refreshKeyChain(unlockKeyBase64, webApi);+ await VaultKeyService.refreshKeyChain({ unlockKey: unlockKeyBase64 }, webApi);} catch (error) {if (error instanceof Error && extractErrorCode(error.message) === AppErrorCode.UNLOCK_KEY_REJECTED) {throw new IncorrectPasswordError();@@ -261,7 +261,7 @@ export class MasterPasswordService {*/private static async assertPasswordOpensChain(unlockKeyBase64: string): Promise<void> {try {- await VaultKeyService.openKeyChain(unlockKeyBase64);+ await VaultKeyService.openKeyChain({ unlockKey: unlockKeyBase64 });} catch (error) {if (error instanceof Error && extractErrorCode(error.message) === AppErrorCode.UNLOCK_KEY_REJECTED) {throw new IncorrectPasswordError();diff --git a/core/client/src/auth/SrpAuthService.ts b/core/client/src/auth/SrpAuthService.tsindex 745a41710..450cf8080 100644--- a/core/client/src/auth/SrpAuthService.ts+++ b/core/client/src/auth/SrpAuthService.ts@@ -1,9 +1,8 @@import { AppErrorCode, formatErrorWithCode } from '../api/errors/AppErrorCodes';import { StorageKeys } from '../constants/StorageKeys';import { createAccountKeyHierarchy, type AccountKeyBlobs, type AccountKeyHierarchy } from '../crypto/AccountKeys';-import { EncryptionUtility } from '../crypto/EncryptionUtility';import { getPlatform } from '../platform/ClientPlatform';-import { rustCore } from '../rust/RustCore';+import { argon2DeriveKey, rustCore } from '../rust/RustCore';import { bytesToBase64 } from '../utilities/Base64';import { isWeakerDerivation } from './DerivationSettings';@@ -30,7 +29,7 @@ export type RegisterRequest = AccountKeyBlobs & {export type PreparedRegistration = {request: RegisterRequest;keys: AccountKeyHierarchy;- derivedKey: string;+ unlockKey: string;};/**@@ -273,7 +272,7 @@ export class SrpAuthService {if (stored && isWeakerDerivation(encryptionSettings, stored.encryptionSettings)) {throw new Error(formatErrorWithCode('The server sent weaker key derivation settings than this device holds', AppErrorCode.UNLOCK_SETTINGS_WEAKENED));}- return bytesToBase64(await EncryptionUtility.deriveKeyFromPassword(password, salt, encryptionSettings));+ return bytesToBase64(await argon2DeriveKey(password, salt, encryptionSettings));}/**@@ -389,7 +388,7 @@ export class SrpAuthService {...hierarchy.accountKeys,},keys: hierarchy,- derivedKey: material.unlockKeyBase64,+ unlockKey: material.unlockKeyBase64,};}}diff --git a/core/client/src/auth/UnlockService.ts b/core/client/src/auth/UnlockService.tsindex df02c94a3..7fabd8963 100644--- a/core/client/src/auth/UnlockService.ts+++ b/core/client/src/auth/UnlockService.ts@@ -6,7 +6,7 @@ import { KeyDerivationUpgradeService } from './KeyDerivationUpgradeService';import { MasterPasswordService } from './MasterPasswordService';import { SrpAuthService } from './SrpAuthService';import { SrpLoginService } from './SrpLoginService';-import { VaultKeyService } from './VaultKeyService';+import { VaultKeyService, type KeyChainKey } from './VaultKeyService';import type { WebApiService } from '../api/WebApiService';import type { UnlockKeyDerivationParams } from '@aliasvault/models/metadata';@@ -75,23 +75,23 @@ export class UnlockService {const loginResponse = await new SrpLoginService(options.webApi).initiateLogin(username!);const unlockKey = await SrpAuthService.deriveUnlockKey(password, loginResponse.salt, loginResponse.encryptionSettings);await UnlockService.storeDerivationParams(loginResponse);- const accountKey = await VaultKeyService.refreshKeyChain(unlockKey, options.webApi);+ const accountKey = await VaultKeyService.refreshKeyChain({ unlockKey }, options.webApi);await UnlockService.upgradeKeyDerivation(password, loginResponse, unlockKey, options.webApi, username!);return accountKey;}/*** Finish an accepted login: fetch and check the key chain, then store the derivation parameters and the Account Key.- * @param unlockKeyBase64 - the unlock key of the login, or the Account Key a mobile app sent+ * @param key - the unlock key of the login, or the Account Key a mobile app sent* @param derivationParams - the derivation parameters of the account's password* @param webApi - the API client, already holding the new session's tokens* @param onKeyChainFailure - ends the session when the key chain cannot be opened, before the error is rethrown* @returns The Account Key.*/- public static async completeKeyChainLogin(unlockKeyBase64: string, derivationParams: UnlockKeyDerivationParams, webApi: WebApiService, onKeyChainFailure?: () => Promise<void>): Promise<string> {+ public static async completeKeyChainLogin(key: KeyChainKey, derivationParams: UnlockKeyDerivationParams, webApi: WebApiService, onKeyChainFailure?: () => Promise<void>): Promise<string> {let accountKey: string;try {- accountKey = await VaultKeyService.refreshKeyChain(unlockKeyBase64, webApi);+ accountKey = await VaultKeyService.refreshKeyChain(key, webApi);} catch (err) {await onKeyChainFailure?.();throw err;diff --git a/core/client/src/auth/VaultKeyService.ts b/core/client/src/auth/VaultKeyService.tsindex a6e096456..6d0d41cce 100644--- a/core/client/src/auth/VaultKeyService.ts+++ b/core/client/src/auth/VaultKeyService.ts@@ -5,11 +5,11 @@import { UnlockMethodType, VaultKeyAlgorithm, type VaultKeyGetResponse, type VaultKeyResponse } from '@aliasvault/models/webapi';import { ApiRequestError } from '../api/errors/ApiRequestError';-import { AppErrorCode, formatErrorWithCode } from '../api/errors/AppErrorCodes';+import { AppErrorCode, extractErrorCode, formatErrorWithCode } from '../api/errors/AppErrorCodes';import { WebApiService } from '../api/WebApiService';import { StorageKeys } from '../constants/StorageKeys';import { getPlatform } from '../platform/ClientPlatform';-import { openAccountKeyChain } from '../rust/RustCore';+import { openKeyChainWithAccountKey, openKeyChainWithUnlockKey } from '../rust/RustCore';import { convertLegacySessionKey } from './LegacyKeyConversion';@@ -35,6 +35,12 @@ export type SessionKeys = {accountKey: string;};+/**+ * The key a key chain is opened with: the unlock key of a password login, or the Account Key a device unlock method or+ * an earlier login stored.+ */+export type KeyChainKey = { unlockKey: string } | { accountKey: string };+/*** Static helper for fetching, caching and opening the account-key unlock chain (KEK → AK → VEK + account keypair).*/@@ -62,17 +68,17 @@ export class VaultKeyService {/*** Right after authentication: fetch the account's key chain from the server, check that the key opens it and* cache it for offline unlock.- * @param keyBase64 - the unlock key (the Argon2id output of the master password) or an Account Key+ * @param key - the unlock key of the password login, or the Account Key a mobile app sent* @param webApi - the API client to use* @returns The Account Key to store for this session.* @throws Error with {@link AppErrorCode.UNLOCK_KEY_REJECTED} when the key does not open the chain (wrong password).*/- public static async refreshKeyChain(keyBase64: string, webApi?: WebApiService): Promise<string> {+ public static async refreshKeyChain(key: KeyChainKey, webApi?: WebApiService): Promise<string> {const result = await VaultKeyService.fetchVaultKey(webApi);if (!result.supported) {// Older server: trust the local cache.- return VaultKeyService.verifyUnlockKey(keyBase64);+ return (await VaultKeyService.openKeyChain(key)).accountKey;}if (!result.vaultKey) {@@ -81,21 +87,21 @@ export class VaultKeyService {throw new Error(formatErrorWithCode('The server holds no key chain for this account', AppErrorCode.KEY_OUT_OF_SYNC));}await getPlatform().storage.removeMany([StorageKeys.ENCRYPTED_VEK, StorageKeys.ENCRYPTED_ACCOUNT_KEY, StorageKeys.ACCOUNT_PUBLIC_KEY, StorageKeys.ENCRYPTED_ACCOUNT_PRIVATE_KEY, StorageKeys.SIGNING_PUBLIC_KEY, StorageKeys.ENCRYPTED_SIGNING_PRIVATE_KEY]);- return keyBase64;+ return VaultKeyService.keyOf(key);}if (result.vaultKey.algorithm !== VaultKeyAlgorithm.Aes256Gcm) {throw new Error(formatErrorWithCode(`Unsupported Account Key algorithm '${result.vaultKey.algorithm}'`, AppErrorCode.VAULT_VERSION_INCOMPATIBLE));}- const keys = await VaultKeyService.openChain(keyBase64, result.vaultKey.encryptedAccountKey, result.vaultKey.encryptedVek ?? null, null);+ const keys = await VaultKeyService.openChain(key, result.vaultKey.encryptedAccountKey, result.vaultKey.encryptedVek ?? null, null);/** A device holding a vault under its unlock key but no chain yet (the account was upgraded on another device) stays* a legacy session: its first sync caches the chain and re-encrypts the stored vault under the VEK in one step.*/- if (keys.accountKey !== keyBase64 && !await VaultKeyService.hasLocalVaultKey() && await getPlatform().storage.get(StorageKeys.ENCRYPTED_VAULT) !== null) {- return keyBase64;+ if ('unlockKey' in key && !await VaultKeyService.hasLocalVaultKey() && await getPlatform().storage.get(StorageKeys.ENCRYPTED_VAULT) !== null) {+ return key.unlockKey;}await VaultKeyService.cacheVaultKeyBlobs(result.vaultKey);@@ -103,13 +109,24 @@ export class VaultKeyService {}/**- * Check offline that a key opens the locally cached chain (an account not yet upgraded has none; its key is the vault key).- * @param keyBase64 - the unlock key derived from the typed password, or an Account Key restored by PIN or WebAuthn+ * Check offline that the unlock key derived from the typed password opens the locally cached chain (an account not yet+ * upgraded has none; its unlock key is the vault key).+ * @param unlockKey - the unlock key derived from the typed password* @returns The Account Key to store for this session.* @throws Error with {@link AppErrorCode.UNLOCK_KEY_REJECTED} when the key does not open the chain (wrong password).*/- public static async verifyUnlockKey(keyBase64: string): Promise<string> {- return (await VaultKeyService.openKeyChain(keyBase64)).accountKey;+ public static async verifyUnlockKey(unlockKey: string): Promise<string> {+ return (await VaultKeyService.openKeyChain({ unlockKey })).accountKey;+ }++ /**+ * Check offline that an Account Key a device unlock method (PIN, passkey) restored opens the locally cached chain.+ * @param accountKey - the restored Account Key+ * @returns The Account Key to store for this session.+ * @throws Error with {@link AppErrorCode.UNLOCK_KEY_REJECTED} when the key does not open the chain (a stale key).+ */+ public static async verifyAccountKey(accountKey: string): Promise<string> {+ return (await VaultKeyService.openKeyChain({ accountKey })).accountKey;}/**@@ -147,15 +164,35 @@ export class VaultKeyService {/*** The keys of the unlocked session, derived from the Account Key and the cached chain, or null when the vault is- * locked. A legacy stored unlock key is replaced by the Account Key here (see LegacyKeyConversion).+ * locked.*/public static async getSessionKeys(): Promise<SessionKeys | null> {- const accountKey = await VaultKeyService.getSessionAccountKey();- if (!accountKey) {+ const storedKey = await VaultKeyService.getSessionAccountKey();+ if (!storedKey) {return null;}- const keys = await VaultKeyService.openKeyChain(accountKey);- await convertLegacySessionKey(accountKey, keys.accountKey);+ return VaultKeyService.openStoredSessionKey(storedKey);+ }++ /**+ * Open the cached chain with the key the session stores: the Account Key. A session that still holds an unlock key+ * (see LegacyKeyConversion) opens the chain with it as such and stores the Account Key in its place.+ * @param storedKey - the key the session stores+ */+ private static async openStoredSessionKey(storedKey: string): Promise<SessionKeys> {+ try {+ return await VaultKeyService.openKeyChain({ accountKey: storedKey });+ } catch (error) {+ if (!(error instanceof Error) || extractErrorCode(error.message) !== AppErrorCode.UNLOCK_KEY_REJECTED) {+ throw error;+ }+ }+ /*+ * LEGACY: the session holds an unlock key from before the account had a key chain.+ * This legacy key conversion call can be removed once all clients have updated to 0.31.0+.+ */+ const keys = await VaultKeyService.openKeyChain({ unlockKey: storedKey });+ await convertLegacySessionKey(storedKey, keys.accountKey);return keys;}@@ -205,11 +242,11 @@ export class VaultKeyService {/*** Open the locally cached chain with a stored or typed key. Without a cached chain (account not yet upgraded) the- * unlock key is the vault encryption key.- * @param keyBase64 - the Account Key or an unlock key+ * key is the vault encryption key.+ * @param key - the unlock key or the Account Key* @throws Error with {@link AppErrorCode.UNLOCK_KEY_REJECTED} when the key does not open the chain.*/- public static async openKeyChain(keyBase64: string): Promise<SessionKeys> {+ public static async openKeyChain(key: KeyChainKey): Promise<SessionKeys> {const storage = getPlatform().storage;const [encryptedAccountKey, encryptedVek, encryptedAccountPrivateKey] = await Promise.all([storage.get<string>(StorageKeys.ENCRYPTED_ACCOUNT_KEY),@@ -217,29 +254,34 @@ export class VaultKeyService {storage.get<string>(StorageKeys.ENCRYPTED_ACCOUNT_PRIVATE_KEY),]);if (!encryptedAccountKey) {+ const keyBase64 = VaultKeyService.keyOf(key);return { vaultEncryptionKey: keyBase64, accountPrivateKey: null, accountKey: keyBase64 };}- return VaultKeyService.openChain(keyBase64, encryptedAccountKey, encryptedVek, encryptedAccountPrivateKey);+ return VaultKeyService.openChain(key, encryptedAccountKey, encryptedVek, encryptedAccountPrivateKey);}/**- * Walk a chain with the Account Key or an unlock key (see the Rust `open_account_key_chain`).- * @param keyBase64 - the Account Key or an unlock key+ * Walk a chain with the unlock key or the Account Key (the Rust `open_key_chain_with_unlock_key` and+ * `open_key_chain_with_account_key`).+ * @param key - the unlock key or the Account Key* @param encryptedAccountKey - the Account Key encrypted with the KEK derived from the unlock key* @param encryptedVek - the VEK encrypted with the Account Key* @param encryptedAccountPrivateKey - the account private key encrypted with the Account Key, or null when the account has none yet*/- private static async openChain(keyBase64: string, encryptedAccountKey: string, encryptedVek: string | null, encryptedAccountPrivateKey: string | null): Promise<SessionKeys> {+ private static async openChain(key: KeyChainKey, encryptedAccountKey: string, encryptedVek: string | null, encryptedAccountPrivateKey: string | null): Promise<SessionKeys> {if (!encryptedVek) {throw new Error('Vault key chain is missing the encrypted VEK');}- const opened = await openAccountKeyChain(keyBase64, encryptedAccountKey, encryptedVek, encryptedAccountPrivateKey);+ const opened = 'unlockKey' in key+ ? await openKeyChainWithUnlockKey(key.unlockKey, encryptedAccountKey, encryptedVek, encryptedAccountPrivateKey)+ : await openKeyChainWithAccountKey(key.accountKey, encryptedVek, encryptedAccountPrivateKey);switch (opened.status) {case 'opened':return { vaultEncryptionKey: opened.vaultEncryptionKey, accountPrivateKey: opened.accountPrivateKey, accountKey: opened.accountKey };case 'unlockKeyRejected':- // E-206: the key does not open the account key, which for the password key type means a wrong password.+ case 'accountKeyRejected':+ // E-206: the key does not open the chain, which for the unlock key means a wrong password.throw new Error(formatErrorWithCode('Failed to decrypt key chain', AppErrorCode.UNLOCK_KEY_REJECTED));default:// E-207: the account key opened, so a failure here is a damaged chain and never a wrong password.@@ -247,6 +289,13 @@ export class VaultKeyService {}}+ /**+ * The base64 key inside a {@link KeyChainKey}.+ */+ private static keyOf(key: KeyChainKey): string {+ return 'unlockKey' in key ? key.unlockKey : key.accountKey;+ }+/*** Persist a server vault-key response's encrypted blobs for offline unlock.* @param vaultKey - the server's vault key responsediff --git a/core/client/src/rust/RustCore.ts b/core/client/src/rust/RustCore.tsindex 733da454d..1f0723690 100644--- a/core/client/src/rust/RustCore.ts+++ b/core/client/src/rust/RustCore.ts@@ -217,10 +217,17 @@ export async function argon2DeriveKey(password: string, salt: string, encryption}/**- * Open a key chain with a stored key: the Account Key, or an unlock key that is then replaced by the Account Key.+ * Open a key chain with the unlock key (base64), the password's Argon2id output. Never accepts the Account Key.*/-export async function openAccountKeyChain(storedKey: string, encryptedAccountKey: string, encryptedVek: string, encryptedAccountPrivateKey: string | null): Promise<KeyChainOpenResult> {- return rustCore().openAccountKeyChain(storedKey, encryptedAccountKey, encryptedVek, encryptedAccountPrivateKey);+export async function openKeyChainWithUnlockKey(unlockKey: string, encryptedAccountKey: string, encryptedVek: string, encryptedAccountPrivateKey: string | null): Promise<KeyChainOpenResult> {+ return rustCore().openKeyChainWithUnlockKey(unlockKey, encryptedAccountKey, encryptedVek, encryptedAccountPrivateKey);+}++/**+ * Open a key chain with the Account Key (base64). Never accepts an unlock key.+ */+export async function openKeyChainWithAccountKey(accountKey: string, encryptedVek: string, encryptedAccountPrivateKey: string | null): Promise<KeyChainOpenResult> {+ return rustCore().openKeyChainWithAccountKey(accountKey, encryptedVek, encryptedAccountPrivateKey);}/**diff --git a/core/client/src/rust/RustCoreBinding.ts b/core/client/src/rust/RustCoreBinding.tsindex 5188159d7..84458dd14 100644--- a/core/client/src/rust/RustCoreBinding.ts+++ b/core/client/src/rust/RustCoreBinding.ts@@ -62,7 +62,8 @@ export interface IRustCore {argon2DeriveKey(password: string, salt: string, encryptionSettings: string): Promise<Uint8Array>;deriveSrpPasswordHash(unlockKeyBase64: string, encryptionType: string): Promise<string>;- openAccountKeyChain(storedKey: string, encryptedAccountKey: string, encryptedVek: string, encryptedAccountPrivateKey: string | null): Promise<KeyChainOpenResult>;+ openKeyChainWithUnlockKey(unlockKey: string, encryptedAccountKey: string, encryptedVek: string, encryptedAccountPrivateKey: string | null): Promise<KeyChainOpenResult>;+ openKeyChainWithAccountKey(accountKey: string, encryptedVek: string, encryptedAccountPrivateKey: string | null): Promise<KeyChainOpenResult>;createAccountKeyHierarchy(unlockKeyBase64: string, publicKeyJwk: string, privateKeyJwk: string): Promise<AccountKeyHierarchy>;reencryptAccountKey(encryptedAccountKey: string, oldUnlockKeyBase64: string, newUnlockKeyBase64: string): Promise<ReencryptedAccountKey | null>;diff --git a/core/client/src/rust/RustCoreTypes.ts b/core/client/src/rust/RustCoreTypes.tsindex 02c3265ec..cf5b7f5c2 100644--- a/core/client/src/rust/RustCoreTypes.ts+++ b/core/client/src/rust/RustCoreTypes.ts@@ -91,12 +91,13 @@ export type PinFailure = {};/**- * The outcome of opening a key chain with a stored key (the Rust `open_account_key_chain`). Keys are base64; on- * success `accountKey` is what the caller stores in place of the key it passed in.+ * The outcome of opening a key chain (the Rust `open_key_chain_with_unlock_key` and `open_key_chain_with_account_key`).+ * Keys are base64; on success `accountKey` is the Account Key the caller stores for later unlocks.*/export type KeyChainOpenResult =| { status: 'opened'; vaultEncryptionKey: string; accountKey: string; accountPrivateKey: string | null }| { status: 'unlockKeyRejected' }+ | { status: 'accountKeyRejected' }| { status: 'keyChainUnreadable'; message: string };/**@@ -117,6 +118,8 @@ export type AccountKeyBlobs = {* A newly created account key hierarchy (the Rust `create_account_key_hierarchy`): the encrypted blobs plus the plaintext halves the client keeps.*/export type AccountKeyHierarchy = {+ /** The Account Key (base64) the session stores. */+ accountKey: string;vaultEncryptionKey: string;accountPrivateKey: string;signingPrivateKey: string;diff --git a/core/client/src/rust/WasmRustCore.ts b/core/client/src/rust/WasmRustCore.tsindex 775721fd5..8f42f02ee 100644--- a/core/client/src/rust/WasmRustCore.ts+++ b/core/client/src/rust/WasmRustCore.ts@@ -100,8 +100,10 @@ export function createWasmRustCore(loadWasm: WasmLoader): IRustCore {return ready(() => core.argon2DeriveKey(password, salt, encryptionSettings));},deriveSrpPasswordHash: (unlockKeyBase64, encryptionType): Promise<string> => ready(() => core.deriveSrpPasswordHash(unlockKeyBase64, encryptionType)),- openAccountKeyChain: (storedKey, encryptedAccountKey, encryptedVek, encryptedAccountPrivateKey): Promise<KeyChainOpenResult> =>- ready(() => core.openAccountKeyChain(storedKey, encryptedAccountKey, encryptedVek, encryptedAccountPrivateKey ?? undefined) as KeyChainOpenResult),+ openKeyChainWithUnlockKey: (unlockKey, encryptedAccountKey, encryptedVek, encryptedAccountPrivateKey): Promise<KeyChainOpenResult> =>+ ready(() => core.openKeyChainWithUnlockKey(unlockKey, encryptedAccountKey, encryptedVek, encryptedAccountPrivateKey ?? undefined) as KeyChainOpenResult),+ openKeyChainWithAccountKey: (accountKey, encryptedVek, encryptedAccountPrivateKey): Promise<KeyChainOpenResult> =>+ ready(() => core.openKeyChainWithAccountKey(accountKey, encryptedVek, encryptedAccountPrivateKey ?? undefined) as KeyChainOpenResult),createAccountKeyHierarchy: (unlockKeyBase64, publicKeyJwk, privateKeyJwk): Promise<AccountKeyHierarchy> =>ready(() => core.createAccountKeyHierarchy(unlockKeyBase64, publicKeyJwk, privateKeyJwk) as AccountKeyHierarchy),reencryptAccountKey: (encryptedAccountKey, oldUnlockKeyBase64, newUnlockKeyBase64): Promise<ReencryptedAccountKey | null> =>diff --git a/core/rust/src/bindings/uniffi_api.rs b/core/rust/src/bindings/uniffi_api.rsindex 79db1ad52..822bfb914 100644--- a/core/rust/src/bindings/uniffi_api.rs+++ b/core/rust/src/bindings/uniffi_api.rs@@ -287,25 +287,36 @@ pub fn derive_srp_password_hash(unlock_key: Vec<u8>, encryption_type: String) ->pub struct KeyChainKeys {pub vault_encryption_key: Vec<u8>,- /// What the caller stores in place of the key it passed in.+ /// The Account Key: what the caller stores for later unlocks.pub account_key: Vec<u8>,/// The account private key (JWK), none when the account has no keypair or it does not open.pub account_private_key: Option<String>,}-/// Open a key chain with a stored key: the Account Key or an unlock key.+impl KeyChainKeys {+ fn from(opened: crate::crypto::key_chain::OpenedKeyChain) -> Result<Self, KeyChainError> {+ let decode = |key: &str| crate::common::encoding::base64_decode(key).map_err(|e| KeyChainError::KeyChainUnreadable(e.to_string()));+ Ok(KeyChainKeys {+ vault_encryption_key: decode(&opened.vault_encryption_key)?,+ account_key: decode(&opened.account_key)?,+ account_private_key: opened.account_private_key.as_ref().map(|key| key.to_string()),+ })+ }+}++/// Open a key chain with the unlock key (the password's Argon2id output).+#[uniffi::export]+pub fn open_key_chain_with_unlock_key(unlock_key: Vec<u8>, encrypted_account_key: String, encrypted_vek: String, encrypted_account_private_key: Option<String>) -> Result<KeyChainKeys, KeyChainError> {+ let unlock_key = zeroize::Zeroizing::new(crate::common::encoding::base64_encode(&unlock_key));+ KeyChainKeys::from(crate::crypto::open_key_chain_with_unlock_key(&unlock_key, &encrypted_account_key, &encrypted_vek, encrypted_account_private_key.as_deref())?)+}++/// Open a key chain with the Account Key.#[uniffi::export]-pub fn open_account_key_chain(stored_key: Vec<u8>, encrypted_account_key: String, encrypted_vek: String, encrypted_account_private_key: Option<String>) -> Result<KeyChainKeys, KeyChainError> {- use crate::common::encoding::{base64_decode, base64_encode};- let stored_key = zeroize::Zeroizing::new(base64_encode(&stored_key));- let opened = crate::crypto::open_account_key_chain(&stored_key, &encrypted_account_key, &encrypted_vek, encrypted_account_private_key.as_deref())?;- let decode = |key: &str| base64_decode(key).map_err(|e| KeyChainError::KeyChainUnreadable(e.to_string()));- Ok(KeyChainKeys {- vault_encryption_key: decode(&opened.vault_encryption_key)?,- account_key: decode(&opened.account_key)?,- account_private_key: opened.account_private_key.as_ref().map(|key| key.to_string()),- })+pub fn open_key_chain_with_account_key(account_key: Vec<u8>, encrypted_vek: String, encrypted_account_private_key: Option<String>) -> Result<KeyChainKeys, KeyChainError> {+ let account_key = zeroize::Zeroizing::new(crate::common::encoding::base64_encode(&account_key));+ KeyChainKeys::from(crate::crypto::open_key_chain_with_account_key(&account_key, &encrypted_vek, encrypted_account_private_key.as_deref())?)}/// A random 32-byte SRP salt as an uppercase hex string.diff --git a/core/rust/src/bindings/wasm.rs b/core/rust/src/bindings/wasm.rsindex f310d345d..e97002b1b 100644--- a/core/rust/src/bindings/wasm.rs+++ b/core/rust/src/bindings/wasm.rs@@ -300,7 +300,7 @@ pub fn derive_srp_password_hash_js(unlock_key_base64: &str, encryption_type: &stcrate::crypto::derive_srp_password_hash(&unlock_key, encryption_type).map(|hash| hash.to_string()).map_err(js_err)}-/// The outcome of `openAccountKeyChain`: `status` is `opened`, `unlockKeyRejected` or `keyChainUnreadable`.+/// The outcome of opening a key chain: `status` is `opened`, `unlockKeyRejected`, `accountKeyRejected` or `keyChainUnreadable`.#[derive(Serialize)]#[serde(rename_all = "camelCase")]struct KeyChainOpenResult {@@ -311,23 +311,35 @@ struct KeyChainOpenResult {message: Option<String>,}-/// Open a key chain with a stored key (the Account Key or an unlock key, base64). On success `accountKey` is what the-/// caller stores in place of the key it passed in.-#[wasm_bindgen(js_name = openAccountKeyChain)]-pub fn open_account_key_chain_js(stored_key: &str, encrypted_account_key: &str, encrypted_vek: &str, encrypted_account_private_key: Option<String>) -> Result<JsValue, JsValue> {- use crate::crypto::KeyChainError;- let result = match crate::crypto::open_account_key_chain(stored_key, encrypted_account_key, encrypted_vek, encrypted_account_private_key.as_deref()) {- Ok(opened) => KeyChainOpenResult {- status: "opened",- vault_encryption_key: Some(opened.vault_encryption_key.to_string()),- account_key: Some(opened.account_key.to_string()),- account_private_key: opened.account_private_key.as_ref().map(|key| key.to_string()),- message: None,- },- Err(KeyChainError::UnlockKeyRejected) => KeyChainOpenResult { status: "unlockKeyRejected", vault_encryption_key: None, account_key: None, account_private_key: None, message: None },- Err(KeyChainError::KeyChainUnreadable(message)) => KeyChainOpenResult { status: "keyChainUnreadable", vault_encryption_key: None, account_key: None, account_private_key: None, message: Some(message) },- };- to_js(&result)+impl KeyChainOpenResult {+ fn from(result: Result<crate::crypto::key_chain::OpenedKeyChain, crate::crypto::KeyChainError>) -> Self {+ use crate::crypto::KeyChainError;+ let rejected = |status: &'static str, message: Option<String>| KeyChainOpenResult { status, vault_encryption_key: None, account_key: None, account_private_key: None, message };+ match result {+ Ok(opened) => KeyChainOpenResult {+ status: "opened",+ vault_encryption_key: Some(opened.vault_encryption_key.to_string()),+ account_key: Some(opened.account_key.to_string()),+ account_private_key: opened.account_private_key.as_ref().map(|key| key.to_string()),+ message: None,+ },+ Err(KeyChainError::UnlockKeyRejected) => rejected("unlockKeyRejected", None),+ Err(KeyChainError::AccountKeyRejected) => rejected("accountKeyRejected", None),+ Err(KeyChainError::KeyChainUnreadable(message)) => rejected("keyChainUnreadable", Some(message)),+ }+ }+}++/// Open a key chain with the unlock key (base64). On success `accountKey` is what the caller stores for later unlocks.+#[wasm_bindgen(js_name = openKeyChainWithUnlockKey)]+pub fn open_key_chain_with_unlock_key_js(unlock_key: &str, encrypted_account_key: &str, encrypted_vek: &str, encrypted_account_private_key: Option<String>) -> Result<JsValue, JsValue> {+ to_js(&KeyChainOpenResult::from(crate::crypto::open_key_chain_with_unlock_key(unlock_key, encrypted_account_key, encrypted_vek, encrypted_account_private_key.as_deref())))+}++/// Open a key chain with the Account Key (base64).+#[wasm_bindgen(js_name = openKeyChainWithAccountKey)]+pub fn open_key_chain_with_account_key_js(account_key: &str, encrypted_vek: &str, encrypted_account_private_key: Option<String>) -> Result<JsValue, JsValue> {+ to_js(&KeyChainOpenResult::from(crate::crypto::open_key_chain_with_account_key(account_key, encrypted_vek, encrypted_account_private_key.as_deref())))}/// A random 32-byte SRP salt as an uppercase hex string.diff --git a/core/rust/src/crypto/key_chain.rs b/core/rust/src/crypto/key_chain.rsindex 6230f91ed..4eefc7083 100644--- a/core/rust/src/crypto/key_chain.rs+++ b/core/rust/src/crypto/key_chain.rs@@ -43,6 +43,7 @@ pub struct AccountKeyBlobs {#[derive(Clone, Serialize, Deserialize, Zeroize, ZeroizeOnDrop)]#[serde(rename_all = "camelCase")]pub struct AccountKeyHierarchy {+ pub account_key: String,pub vault_encryption_key: String,pub account_private_key: String,pub signing_private_key: String,@@ -53,12 +54,7 @@ pub struct AccountKeyHierarchy {impl fmt::Debug for AccountKeyHierarchy {fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {- f.debug_struct("AccountKeyHierarchy")- .field("vault_encryption_key", &"<redacted>")- .field("account_private_key", &"<redacted>")- .field("signing_private_key", &"<redacted>")- .field("account_keys", &self.account_keys)- .finish()+ f.debug_struct("AccountKeyHierarchy").field("account_keys", &self.account_keys).finish_non_exhaustive()}}@@ -149,10 +145,14 @@ pub fn account_signing_key_fingerprint(encrypted_signing_private_key: &str, acco#[cfg_attr(feature = "uniffi", derive(uniffi::Error))]#[cfg_attr(feature = "uniffi", uniffi(flat_error))]pub enum KeyChainError {- /// The stored key is neither the Account Key nor an unlock key that opens it (wrong password or PIN).- #[error("The key does not open the account key")]+ /// The unlock key does not open the Account Key (wrong password).+ #[error("The unlock key does not open the account key")]UnlockKeyRejected,+ /// The Account Key does not open the VEK: a stored Account Key that is not this chain's.+ #[error("The account key does not open the vault encryption key")]+ AccountKeyRejected,+/// The Account Key opened but the VEK does not open under it: a damaged chain, never a wrong password.#[error("The key chain is unreadable: {0}")]KeyChainUnreadable(String),@@ -162,27 +162,35 @@ pub enum KeyChainError {pub struct OpenedKeyChain {pub vault_encryption_key: Zeroizing<String>,- /// The Account Key: what the caller stores for later unlocks, in place of the key it passed in.+ /// The Account Key: what the caller stores for later unlocks.pub account_key: Zeroizing<String>,/// None when the account has no keypair or its private key does not open; grants then stay closed.pub account_private_key: Option<Zeroizing<String>>,}-/// Open a key chain with a stored key: the Account Key, or an unlock key stored before the switch to the Account Key.-pub fn open_account_key_chain(stored_key: &str, encrypted_account_key: &str, encrypted_vek: &str, encrypted_account_private_key: Option<&str>) -> Result<OpenedKeyChain, KeyChainError> {- let (account_key, vault_encryption_key) = match unwrap_key(encrypted_vek, stored_key, aad::PERSONAL_VEK) {- Ok(vek) => (Zeroizing::new(stored_key.to_string()), vek),- Err(_) => {- let account_key = unwrap_account_key(encrypted_account_key, stored_key).map_err(|_| KeyChainError::UnlockKeyRejected)?;- let vek = unwrap_key(encrypted_vek, &account_key, aad::PERSONAL_VEK).map_err(|e| KeyChainError::KeyChainUnreadable(e.to_string()))?;- (account_key, vek)- }- };- let account_private_key = encrypted_account_private_key.filter(|e| !e.is_empty()).and_then(|e| open_account_private_key(e, &account_key).ok()).map(Zeroizing::new);+/// Open a key chain with the unlock key (the password's Argon2id output): the KEK derived from it unwraps the Account+/// Key, which unwraps the VEK. Never accepts the Account Key itself; see [`open_key_chain_with_account_key`].+pub fn open_key_chain_with_unlock_key(unlock_key_base64: &str, encrypted_account_key: &str, encrypted_vek: &str, encrypted_account_private_key: Option<&str>) -> Result<OpenedKeyChain, KeyChainError> {+ let account_key = unwrap_account_key(encrypted_account_key, unlock_key_base64).map_err(|_| KeyChainError::UnlockKeyRejected)?;+ let vault_encryption_key = unwrap_key(encrypted_vek, &account_key, aad::PERSONAL_VEK).map_err(|e| KeyChainError::KeyChainUnreadable(e.to_string()))?;+ let account_private_key = open_optional_account_private_key(encrypted_account_private_key, &account_key);Ok(OpenedKeyChain { vault_encryption_key, account_key, account_private_key })}+/// Open a key chain with the Account Key, as a device unlock method or an unlocked session holds it. Never accepts an+/// unlock key; see [`open_key_chain_with_unlock_key`].+pub fn open_key_chain_with_account_key(account_key_base64: &str, encrypted_vek: &str, encrypted_account_private_key: Option<&str>) -> Result<OpenedKeyChain, KeyChainError> {+ let vault_encryption_key = unwrap_key(encrypted_vek, account_key_base64, aad::PERSONAL_VEK).map_err(|_| KeyChainError::AccountKeyRejected)?;+ let account_private_key = open_optional_account_private_key(encrypted_account_private_key, account_key_base64);+ Ok(OpenedKeyChain { vault_encryption_key, account_key: Zeroizing::new(account_key_base64.to_string()), account_private_key })+}++/// The account private key when the chain carries one that opens; a failure keeps grants closed, not the vault.+fn open_optional_account_private_key(encrypted_account_private_key: Option<&str>, account_key_base64: &str) -> Option<Zeroizing<String>> {+ encrypted_account_private_key.filter(|e| !e.is_empty()).and_then(|e| open_account_private_key(e, account_key_base64).ok()).map(Zeroizing::new)+}+/// Create a new account key hierarchy wrapped under the KEK derived from an unlock key.pub fn create_account_key_hierarchy(unlock_key_base64: &str) -> VaultResult<AccountKeyHierarchy> {create_account_key_hierarchy_with_key_pair(unlock_key_base64, &generate_rsa_key_pair()?)@@ -207,7 +215,7 @@ pub fn create_account_key_hierarchy_with_key_pair(unlock_key_base64: &str, key_paccount_public_key_signature: signing::sign(&signing_key_pair.private_key, &account_public_key_message)?,};- Ok(AccountKeyHierarchy { vault_encryption_key, account_private_key: key_pair.private_key.clone(), signing_private_key: signing_key_pair.private_key.clone(), account_keys })+ Ok(AccountKeyHierarchy { account_key: account_key.to_string(), vault_encryption_key, account_private_key: key_pair.private_key.clone(), signing_private_key: signing_key_pair.private_key.clone(), account_keys })}/// The Account Key re-encrypted for a new password.@@ -251,9 +259,8 @@ impl fmt::Debug for RotatedAccountKeys {/// wrapped under the KEK of `new_unlock_key_base64`.pub fn rotate_account_keys(new_unlock_key_base64: &str, key_pair: &RsaKeyPair) -> VaultResult<RotatedAccountKeys> {let hierarchy = create_account_key_hierarchy_with_key_pair(new_unlock_key_base64, key_pair)?;- let account_key = unwrap_account_key(&hierarchy.account_keys.encrypted_account_key, new_unlock_key_base64)?;Ok(RotatedAccountKeys {- account_key: account_key.to_string(),+ account_key: hierarchy.account_key.clone(),vault_encryption_key: hierarchy.vault_encryption_key.clone(),account_private_key: hierarchy.account_private_key.clone(),signing_private_key: hierarchy.signing_private_key.clone(),