Privacy-first password manager with built-in email aliasing. Fully encrypted and self-hostable.
Add explicit LegacyKeyConversion (#2469)
Leendert de Borstbdd4e2a4e037
diff --git a/apps/browser-extension/src/entrypoints/popup/pages/settings/security/ChangePasswordSettings.tsx b/apps/browser-extension/src/entrypoints/popup/pages/settings/security/ChangePasswordSettings.tsxindex bf3a85be1..91bf955e6 100644--- a/apps/browser-extension/src/entrypoints/popup/pages/settings/security/ChangePasswordSettings.tsx+++ b/apps/browser-extension/src/entrypoints/popup/pages/settings/security/ChangePasswordSettings.tsx@@ -15,7 +15,6 @@ import { useWebApi } from '@/entrypoints/popup/context/WebApiContext';import { useVaultSync } from '@/entrypoints/popup/hooks/useVaultSync';import { logFailure } from '@/utils/Diagnostics';-import { removeAndDisablePin } from '@/utils/PinUnlockService';type PasswordInputProps = {id: string;@@ -123,13 +122,8 @@ const ChangePasswordSettings: React.FC = () => {try {showLoading();+ // The PIN protects the Account Key, which a password change leaves as it is, so PIN unlock keeps working.await MasterPasswordService.changePassword(webApi, currentPassword, newPassword);-- /*- * The PIN protects the key derived from the old password, which no longer opens the account key chain.- * TODO: refactor this to automatically update the PIN instead of disabling it?- */- await removeAndDisablePin();setCurrentPassword('');setNewPassword('');setConfirmPassword('');diff --git a/apps/browser-extension/src/utils/LegacyKeyConversion.ts b/apps/browser-extension/src/utils/LegacyKeyConversion.tsnew file mode 100644index 000000000..b45024456--- /dev/null+++ b/apps/browser-extension/src/utils/LegacyKeyConversion.ts@@ -0,0 +1,23 @@+import { setupPin } from '@/utils/PinUnlockService';++/*+ * Legacy conversion of a stored unlock key to 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 session key itself converts in core/client `convertLegacySessionKey`.+ *+ * TODO: remove once accounts without a key chain (pre-0.31.0) are no longer supported.+ */++/**+ * Re-encrypt the PIN with the Account Key when it still protected an unlock key.+ * @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+ */+export async function convertLegacyPinKey(pin: string, pinKey: string, accountKey: string): Promise<void> {+ if (accountKey !== pinKey) {+ await setupPin(pin, accountKey);+ }+}diff --git a/apps/browser-extension/src/utils/PinUnlockService.ts b/apps/browser-extension/src/utils/PinUnlockService.tsindex 3ef3a2739..758188b21 100644--- a/apps/browser-extension/src/utils/PinUnlockService.ts+++ b/apps/browser-extension/src/utils/PinUnlockService.ts@@ -10,7 +10,7 @@ import { browser, storage } from '#imports';* PinUnlockService - Handles PIN-based vault unlock** This service allows users to set a 6-8 digit PIN to unlock their vault instead- * of entering their full master password. The unlock key (the password-derived KEK)+ * of entering their full master password. The session's stored key (the Account Key)* is encrypted with a key derived from the PIN and stored locally.** Security features:@@ -150,7 +150,7 @@ export async function isPinLocked(): Promise<boolean> {* Encrypts the unlock key with the PIN and stores it** @param pin - The PIN to set (6-8 digits)- * @param unlockKey - The base64-encoded unlock key to protect+ * @param unlockKey - The base64-encoded stored key to protect (VaultKeyService.getSessionUnlockKey)*/export async function setupPin(pin: string, unlockKey: string): Promise<void> {if (!isValidPin(pin)) {@@ -202,10 +202,10 @@ export async function setupPin(pin: string, unlockKey: string): Promise<void> {/*** Unlock with PIN- * Returns the decrypted unlock key (the password-derived KEK)+ * Returns the decrypted stored key (the Account Key, or an unlock key from before the account had a key chain)** @param pin - The PIN to use for unlocking- * @returns The decrypted unlock key (base64), which opens the account key chain+ * @returns The decrypted key (base64), which opens the account key chain*/export async function unlockWithPin(pin: string): Promise<string> {if (!isValidPin(pin)) {diff --git a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/pinunlock/PinUnlockActivity.kt b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/pinunlock/PinUnlockActivity.ktindex 396f67dff..f43335e2d 100644--- a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/pinunlock/PinUnlockActivity.kt+++ b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/pinunlock/PinUnlockActivity.kt@@ -60,13 +60,13 @@ class PinUnlockActivity : AppCompatActivity() {/** Result code when PIN was disabled due to max attempts. */const val RESULT_PIN_DISABLED = 100- /** Intent extra key for the unlock key, the password-derived KEK (returned in unlock mode). */+ /** Intent extra key for the key the PIN protects, the Account Key (returned in unlock mode). */const val EXTRA_UNLOCK_KEY = "unlock_key"/** Intent extra key for the mode (unlock or setup). */const val EXTRA_MODE = "mode"- /** Intent extra key for the unlock key (the password-derived KEK) the PIN protects during setup. */+ /** Intent extra key for the key the PIN protects during setup (the session's Account Key). */const val EXTRA_SETUP_UNLOCK_KEY = "setup_unlock_key"/** Intent extra key for custom title (optional). */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.ktnew file mode 100644index 000000000..493086cc5--- /dev/null+++ b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/LegacyKeyConversion.kt@@ -0,0 +1,54 @@+package net.aliasvault.app.vaultstore++import android.util.Base64+import android.util.Log+import net.aliasvault.app.vaultstore.keystoreprovider.KeystoreOperationCallback+import net.aliasvault.app.vaultstore.keystoreprovider.KeystoreProvider++/**+ * Legacy conversion of a stored unlock key to the Account Key.+ *+ * Before 0.31.0 the keystore and the PIN protected the unlock key (the Argon2id output of the master password). Since+ * then they protect the Account Key. A key stored before the account had a key chain (a 0.30.x install, or an account+ * upgraded on another device) still opens the chain; these helpers then store the Account Key in its place, once.+ *+ * TODO: remove once accounts without a key chain (pre-0.31.0) are no longer supported.+ */+internal object LegacyKeyConversion {+ private const val TAG = "LegacyKeyConversion"++ /**+ * Re-encrypt the PIN with the Account Key when it still protected an unlock key.+ */+ fun convertPinKey(pin: VaultPin, pinValue: String, pinKey: String, accountKey: String) {+ if (accountKey == pinKey) {+ return+ }+ try {+ pin.setupPin(pinValue, accountKey)+ } catch (e: Exception) {+ Log.w(TAG, "Could not re-encrypt the PIN key, will retry on the next PIN unlock", e)+ }+ }++ /**+ * Store the Account Key in the keystore when it still held an unlock key.+ */+ fun convertKeystoreKey(keystoreProvider: KeystoreProvider, keystoreKey: ByteArray, accountKey: ByteArray) {+ if (accountKey.contentEquals(keystoreKey)) {+ return+ }+ keystoreProvider.storeKey(+ key = Base64.encodeToString(accountKey, Base64.NO_WRAP),+ object : KeystoreOperationCallback {+ override fun onSuccess(result: String) {+ Log.d(TAG, "Replaced the keystore unlock key with the account key")+ }++ override fun onError(e: Exception) {+ Log.d(TAG, "Could not replace the keystore unlock key yet: ${e.message}")+ }+ },+ )+ }+}diff --git a/apps/mobile-app/context/DbContext.tsx b/apps/mobile-app/context/DbContext.tsxindex a59e9ef7b..ae40d6160 100644--- a/apps/mobile-app/context/DbContext.tsx+++ b/apps/mobile-app/context/DbContext.tsx@@ -112,8 +112,9 @@ export const DbProvider: React.FC<{ children: React.ReactNode }> = ({ children }}, []);/**- * Store the unlock key (the password-derived KEK) in the Native module (in memory and optionally keychain). The- * native module opens the account key chain with it, which gives the vault encryption key of the session.+ * Store the unlock key (the password's Argon2id output) in the Native module (in memory and optionally keychain). The+ * native module opens the account key chain with it and keeps the Account Key it yields, which gives the vault+ * encryption key of the session.** @param derivedKey The password-derived unlock key*/@@ -265,7 +266,7 @@ export const DbProvider: React.FC<{ children: React.ReactNode }> = ({ children }* Test if the database is working with the provided (to be stored) unlock key by performing a simple query.* Uses two-step process: first init key in memory, verify it works, then persist to keystore.* This prevents overwriting a valid key with an invalid one if user enters wrong password.- * @param derivedKey The unlock key (the password-derived KEK) to test with+ * @param derivedKey The unlock key (the password's Argon2id output) to test with* @returns true if the database is working* @throws Error with error code if unlock fails - caller should handle the error*/@@ -294,7 +295,7 @@ export const DbProvider: React.FC<{ children: React.ReactNode }> = ({ children }/*** Verify if the provided unlock key is valid.- * @param derivedKey The unlock key (the password-derived KEK) to verify+ * @param derivedKey The unlock key (the password's Argon2id output) to verify* @returns true if the key is valid, false if invalid (wrong password)*/const verifyUnlockKey = useCallback(async (derivedKey: string): Promise<boolean> => {diff --git a/apps/mobile-app/ios/VaultModels/UnlockMethodType.swift b/apps/mobile-app/ios/VaultModels/UnlockMethodType.swiftindex 373f417d4..d8340c1e1 100644--- a/apps/mobile-app/ios/VaultModels/UnlockMethodType.swift+++ b/apps/mobile-app/ios/VaultModels/UnlockMethodType.swift@@ -7,7 +7,7 @@ import Foundation/// Unlock methods a user can enroll. Each enrolled method stores one copy of the user's Account Key,/// encrypted with a KEK derived from that method's secret.public struct UnlockMethodType {- /// Master password: the KEK is derived from the password via Argon2.+ /// Master password: Argon2id of the password gives the unlock key, which the KEK and SRP input are HKDF-derived from.public static let password = "password"/// All known UnlockMethodType tokens.diff --git a/apps/mobile-app/ios/VaultStoreKit/VaultStore+Crypto.swift b/apps/mobile-app/ios/VaultStoreKit/VaultStore+Crypto.swiftindex f7215b5f5..3b90a2062 100644--- a/apps/mobile-app/ios/VaultStoreKit/VaultStore+Crypto.swift+++ b/apps/mobile-app/ios/VaultStoreKit/VaultStore+Crypto.swift@@ -284,7 +284,7 @@ extension VaultStore {return try openAccountKeyChain(with: try getUnlockKey()).vaultEncryptionKey}- /// Get the unlock key - the password-derived KEK the keychain and PIN protect.+ /// Get the session's stored key, which the keychain and PIN protect.internal func getUnlockKey() throws -> Data {if let key = self.unlockKey {return key@@ -339,6 +339,9 @@ extension VaultStore {do {try openSession(unlockKey: keyData)+ if let accountKey = self.unlockKey {+ convertLegacyKeychainKey(keychainKey: keyData, accountKey: accountKey)+ }} catch let vaultError as AppError {print("The unlock 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.swiftnew file mode 100644index 000000000..d4b19bc57--- /dev/null+++ b/apps/mobile-app/ios/VaultStoreKit/VaultStore+LegacyKeyConversion.swift@@ -0,0 +1,26 @@+import Foundation++/// Legacy conversion of a stored unlock key to the Account Key.+///+/// Before 0.31.0 the keychain and the PIN protected the unlock key (the Argon2id output of the master password). Since+/// then they protect the Account Key. A key stored before the account had a key chain (a 0.30.x install, or an account+/// upgraded on another device) still opens the chain; these helpers then store the Account Key in its place, once.+///+/// TODO: remove once accounts without a key chain (pre-0.31.0) are no longer supported.+extension VaultStore {+ /// 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 }+ do {+ try encryptKeyWithPin(accountKey, pin: pin)+ } catch {+ print("Could not re-encrypt the PIN key, will retry on the next PIN unlock: \(error)")+ }+ }++ /// Store the Account Key in the keychain when it still held an unlock key.+ internal func convertLegacyKeychainKey(keychainKey: Data, accountKey: Data) {+ guard accountKey != keychainKey, enabledAuthMethods.contains(.faceID), isKeystoreAvailable() else { return }+ try? storeKeyInKeychain(accountKey)+ }+}diff --git a/apps/mobile-app/ios/VaultStoreKit/VaultStore+Pin.swift b/apps/mobile-app/ios/VaultStoreKit/VaultStore+Pin.swiftindex ae70be105..0277261d0 100644--- a/apps/mobile-app/ios/VaultStoreKit/VaultStore+Pin.swift+++ b/apps/mobile-app/ios/VaultStoreKit/VaultStore+Pin.swift@@ -53,9 +53,13 @@ extension VaultStore {throw AppError.biometricNotAvailable}- // Get the unlock key from memory (vault must be unlocked): the PIN protects the KEK, never the vault key- let unlockKey = try getUnlockKey()+ // The session's stored key (vault must be unlocked): the PIN protects the Account Key, never the vault key+ try encryptKeyWithPin(try getUnlockKey(), pin: pin)+ print("PIN unlock enabled successfully")+ }+ /// Encrypt a stored key with a key derived from the PIN and keep it in the keychain.+ internal func encryptKeyWithPin(_ unlockKey: Data, pin: String) throws {// Generate random saltvar salt = Data(count: 16)let result = salt.withUnsafeMutableBytes {@@ -85,19 +89,25 @@ extension VaultStore {userDefaults.set(true, forKey: VaultConstants.pinEnabledKey)userDefaults.set(pin.count, forKey: Self.pinLengthKey)userDefaults.synchronize()-- print("PIN unlock enabled successfully")}// MARK: - PIN Unlock Methods/// Unlock with PIN- /// Returns the decrypted unlock key (the password-derived KEK)+ /// Returns the decrypted stored key////// - Parameter pin: The PIN to use for unlocking- /// - Returns: The decrypted unlock key (base64), to open the session with+ /// - Returns: The decrypted key (base64), to open the session with/// - 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+ convertLegacyPinKey(pin: pin, pinKey: pinProtectedKey, accountKey: accountKey)+ return accountKey.base64EncodedString()+ }++ /// Decrypt the key the PIN protects, counting a failure against the PIN attempts.+ private func decryptPinProtectedKey(_ pin: String) throws -> Data {do {// Retrieve encrypted key and salt from keychainlet (encryptedKey, salt) = try retrievePinDataFromKeychain()@@ -114,8 +124,7 @@ extension VaultStore {try storePinFailedAttemptsInKeychain(0)markSuccessfulAuth()- // Return the decrypted unlock key as base64.- return decryptedKey.base64EncodedString()+ return decryptedKey} catch {// Increment failed attemptslet currentAttempts = getPinFailedAttempts()diff --git a/apps/mobile-app/utils/SqliteClient.ts b/apps/mobile-app/utils/SqliteClient.tsindex 53d8a3c2e..d827dafb5 100644--- a/apps/mobile-app/utils/SqliteClient.ts+++ b/apps/mobile-app/utils/SqliteClient.ts@@ -182,8 +182,8 @@ class SqliteClient {}/**- * Open a session in memory with the unlock key (the password-derived KEK), without keychain persistence.- * Use this to test if a password-derived key is valid before persisting.+ * Open a session in memory with the unlock key or a stored Account Key, without keychain persistence.+ * Use this to test if a key is valid before persisting.** @param base64UnlockKey The base64 encoded unlock key*/@@ -197,7 +197,7 @@ class SqliteClient {}/**- * Open a session with the unlock key (the password-derived KEK) AND persist it to keychain (may trigger biometric prompt).+ * Open a session with the unlock key or a stored Account Key AND persist the Account Key to keychain (may trigger biometric prompt).** @param base64UnlockKey The base64 encoded unlock key*/diff --git a/core/client/src/auth/LegacyKeyConversion.ts b/core/client/src/auth/LegacyKeyConversion.tsnew file mode 100644index 000000000..cf7c44fc7--- /dev/null+++ b/core/client/src/auth/LegacyKeyConversion.ts@@ -0,0 +1,23 @@+import { StorageKeys } from '../constants/StorageKeys';+import { getPlatform } from '../platform/ClientPlatform';++/*+ * Legacy conversion of a stored unlock key to the Account Key.+ *+ * Before 0.31.0 the session stored the unlock key (the Argon2id output of the master password). Since then it stores+ * the Account Key. A key stored before the account had a key chain (an account upgraded on another device) still+ * opens the chain; the session then stores the Account Key in its place, once.+ *+ * TODO: remove once accounts without a key chain (pre-0.31.0) are no longer supported.+ */++/**+ * Store the Account Key in the session when the session still held an unlock key.+ * @param sessionKey - the key the session held+ * @param accountKey - the Account Key the chain opened with it+ */+export async function convertLegacySessionKey(sessionKey: string, accountKey: string): Promise<void> {+ if (accountKey !== sessionKey) {+ await getPlatform().storage.set(StorageKeys.UNLOCK_KEY, accountKey);+ }+}diff --git a/core/client/src/auth/VaultKeyService.ts b/core/client/src/auth/VaultKeyService.tsindex 62d91abd0..6857894de 100644--- a/core/client/src/auth/VaultKeyService.ts+++ b/core/client/src/auth/VaultKeyService.ts@@ -8,8 +8,10 @@ import { ApiRequestError } from '../api/errors/ApiRequestError';import { AppErrorCode, formatErrorWithCode } from '../api/errors/AppErrorCodes';import { WebApiService } from '../api/WebApiService';import { StorageKeys } from '../constants/StorageKeys';-import { EncryptionUtility } from '../crypto/EncryptionUtility';import { getPlatform } from '../platform/ClientPlatform';+import { openAccountKeyChain } from '../rust/RustCore';++import { convertLegacySessionKey } from './LegacyKeyConversion';import type { UnlockKeyDerivationParams } from '@aliasvault/models/metadata';@@ -22,13 +24,15 @@ export type FetchVaultKeyResult = {};/**- * The keys an unlock key opens.+ * The keys a stored key opens.*/export type SessionKeys = {/** The vault encryption key (VEK). */vaultEncryptionKey: string;/** The account private key (JWK). */accountPrivateKey: string | null;+ /** The Account Key, which the session stores for later unlocks (until the account is upgraded: its vault key). */+ accountKey: string;};/**@@ -55,37 +59,39 @@ export class VaultKeyService {}/**- * Right after authentication: fetch the account's key chain from the server, check that the unlock key opens it- * and cache it for offline unlock.- * @param unlockKeyBase64 - the password-derived key (the KEK)+ * 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 unlockKeyBase64 - the unlock key (the Argon2id output of the master password) or a stored Account Key* @param webApi - the API client to use+ * @returns The key to store for this session (see {@link SessionKeys.accountKey}).* @throws Error with {@link AppErrorCode.UNLOCK_KEY_REJECTED} when the key does not open the chain (wrong password).*/- public static async refreshKeyChain(unlockKeyBase64: string, webApi?: WebApiService): Promise<void> {+ public static async refreshKeyChain(unlockKeyBase64: string, webApi?: WebApiService): Promise<string> {const result = await VaultKeyService.fetchVaultKey(webApi);if (!result.supported) {// Older server: trust the local cache.- await VaultKeyService.verifyUnlockKey(unlockKeyBase64);- return;+ return VaultKeyService.verifyUnlockKey(unlockKeyBase64);}if (!result.vaultKey) {await getPlatform().storage.removeMany([StorageKeys.ENCRYPTED_VEK, StorageKeys.ENCRYPTED_ACCOUNT_KEY, StorageKeys.ACCOUNT_PUBLIC_KEY, StorageKeys.ENCRYPTED_ACCOUNT_PRIVATE_KEY]);- return;+ return unlockKeyBase64;}- await VaultKeyService.openChain(unlockKeyBase64, result.vaultKey.encryptedAccountKey, result.vaultKey.encryptedVek ?? null, null);+ const keys = await VaultKeyService.openChain(unlockKeyBase64, result.vaultKey.encryptedAccountKey, result.vaultKey.encryptedVek ?? null, null);await VaultKeyService.cacheVaultKeyBlobs(result.vaultKey);+ return keys.accountKey;}/**- * Check offline that the unlock key opens the locally cached chain. A legacy account has no chain to check against.- * @param unlockKeyBase64 - the password-derived key (the KEK), typed in or restored by PIN+ * Check offline that a key opens the locally cached chain (an account not yet upgraded has none; its key is the vault key).+ * @param unlockKeyBase64 - the unlock key derived from the typed password, or a key restored by PIN or WebAuthn+ * @returns The key to store for this session (see {@link SessionKeys.accountKey}).* @throws Error with {@link AppErrorCode.UNLOCK_KEY_REJECTED} when the key does not open the chain (wrong password).*/- public static async verifyUnlockKey(unlockKeyBase64: string): Promise<void> {- await VaultKeyService.openKeyChain(unlockKeyBase64);+ public static async verifyUnlockKey(unlockKeyBase64: string): Promise<string> {+ return (await VaultKeyService.openKeyChain(unlockKeyBase64)).accountKey;}/**@@ -115,18 +121,25 @@ export class VaultKeyService {}/**- * The unlock key of this session (the password-derived KEK), or null when the vault is locked.+ * The stored key of this session (see {@link SessionKeys.accountKey}), or null when the vault is locked.*/public static async getSessionUnlockKey(): Promise<string | null> {return (await getPlatform().storage.get(StorageKeys.UNLOCK_KEY)) as string | null;}/**- * The keys of the unlocked session, derived from the unlock key and the cached chain, or null when the vault is locked.+ * The keys of the unlocked session, derived from the stored key and the cached chain, or null when the vault is+ * locked. A stored unlock key is replaced by the Account Key here, e.g. after a sync accepted a chain created on+ * another device.*/public static async getSessionKeys(): Promise<SessionKeys | null> {const unlockKey = await VaultKeyService.getSessionUnlockKey();- return unlockKey ? VaultKeyService.openKeyChain(unlockKey) : null;+ if (!unlockKey) {+ return null;+ }+ const keys = await VaultKeyService.openKeyChain(unlockKey);+ await convertLegacySessionKey(unlockKey, keys.accountKey);+ return keys;}/**@@ -152,23 +165,24 @@ export class VaultKeyService {}/**- * Persist new account key after a local password change. The session moves onto the new unlock key with it.- * @param newEncryptedAccountKey - the Account Key encrypted with the new password-derived KEK- * @param derivationParams - the KEK derivation parameters of the new password- * @param newUnlockKeyBase64 - the new password-derived KEK+ * Persist the new account key after a local password change. The session stores the Account Key, which the change+ * leaves as it is.+ * @param newEncryptedAccountKey - the Account Key encrypted with the KEK of the new password+ * @param derivationParams - the unlock key derivation parameters of the new password+ * @param accountKeyBase64 - the Account Key*/- public static async persistNewAccountKey(newEncryptedAccountKey: string, derivationParams: UnlockKeyDerivationParams, newUnlockKeyBase64: string): Promise<void> {+ public static async persistNewAccountKey(newEncryptedAccountKey: string, derivationParams: UnlockKeyDerivationParams, accountKeyBase64: string): Promise<void> {await getPlatform().storage.setMany([{ key: StorageKeys.ENCRYPTED_ACCOUNT_KEY, value: newEncryptedAccountKey },{ key: StorageKeys.UNLOCK_KEY_DERIVATION_PARAMS, value: derivationParams },- { key: StorageKeys.UNLOCK_KEY, value: newUnlockKeyBase64 },+ { key: StorageKeys.UNLOCK_KEY, value: accountKeyBase64 },]);}/**- * Open the locally cached chain with the unlock key. Without a cached chain (legacy account) the unlock key is- * the vault encryption key.- * @param unlockKeyBase64 - the password-derived key (the KEK)+ * 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 unlockKeyBase64 - the Account Key or an unlock key* @throws Error with {@link AppErrorCode.UNLOCK_KEY_REJECTED} when the key does not open the chain.*/public static async openKeyChain(unlockKeyBase64: string): Promise<SessionKeys> {@@ -179,15 +193,15 @@ export class VaultKeyService {storage.get<string>(StorageKeys.ENCRYPTED_ACCOUNT_PRIVATE_KEY),]);if (!encryptedAccountKey) {- return { vaultEncryptionKey: unlockKeyBase64, accountPrivateKey: null };+ return { vaultEncryptionKey: unlockKeyBase64, accountPrivateKey: null, accountKey: unlockKeyBase64 };}return VaultKeyService.openChain(unlockKeyBase64, encryptedAccountKey, encryptedVek, encryptedAccountPrivateKey);}/**- * Walk a chain: the unlock key decrypts the Account Key, which decrypts the VEK and the account private key.- * @param unlockKeyBase64 - the password-derived key (the KEK)- * @param encryptedAccountKey - the Account Key encrypted with the KEK+ * Walk a chain with the Account Key or an unlock key (see the Rust `open_account_key_chain`).+ * @param unlockKeyBase64 - the Account Key or an unlock 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*/@@ -196,20 +210,17 @@ export class VaultKeyService {throw new Error('Vault key chain is missing the encrypted VEK');}- // E-206: the unlock key does not open the account key, which for the password key type means a wrong password.- const accountKey = await VaultKeyService.decryptKeyOrThrow(encryptedAccountKey, unlockKeyBase64, AppErrorCode.UNLOCK_KEY_REJECTED);- // E-207: the account key opened, so a failure here is a damaged chain and never a wrong password.- const vaultEncryptionKey = await VaultKeyService.decryptKeyOrThrow(encryptedVek, accountKey, AppErrorCode.KEY_CHAIN_UNREADABLE);-- let accountPrivateKey: string | null = null;- if (encryptedAccountPrivateKey) {- try {- accountPrivateKey = await EncryptionUtility.symmetricDecrypt(encryptedAccountPrivateKey, accountKey);- } catch {- // A stale/corrupt private-key blob must not fail the unlock; grant decryption degrades until the next login.- }+ const opened = await openAccountKeyChain(unlockKeyBase64, encryptedAccountKey, 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.+ 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.+ throw new Error(formatErrorWithCode('Failed to decrypt key chain', AppErrorCode.KEY_CHAIN_UNREADABLE));}- return { vaultEncryptionKey, accountPrivateKey };}/**@@ -229,20 +240,6 @@ export class VaultKeyService {await getPlatform().storage.removeMany([StorageKeys.ACCOUNT_PUBLIC_KEY, StorageKeys.ENCRYPTED_ACCOUNT_PRIVATE_KEY]);}}-- /**- * Decrypt an encrypted key blob, reporting a failure under the code of the chain step it belongs to.- * @param encryptedKey - encrypted key blob- * @param decryptingKeyBase64 - the key that decrypts it- * @param failureCode - the error code a failure of this step carries- */- private static async decryptKeyOrThrow(encryptedKey: string, decryptingKeyBase64: string, failureCode: AppErrorCode): Promise<string> {- try {- return await EncryptionUtility.decryptVaultEncryptionKey(encryptedKey, decryptingKeyBase64);- } catch {- throw new Error(formatErrorWithCode('Failed to decrypt key chain', failureCode));- }- }}export default VaultKeyService;