Privacy-first password manager with built-in email aliasing. Fully encrypted and self-hostable.
Refactor session name convention to accountKey (#2469)
Leendert de Borstfc7580fbad1b
diff --git a/apps/browser-extension/src/entrypoints/background.ts b/apps/browser-extension/src/entrypoints/background.tsindex c562f0749..b1100d1e0 100644--- a/apps/browser-extension/src/entrypoints/background.ts+++ b/apps/browser-extension/src/entrypoints/background.ts@@ -12,7 +12,7 @@ import { handleGetWebAuthnSettings, handleWebAuthnCreate, handleWebAuthnGet, hanimport { handleOpenPopup, handlePopupWithItem, handleOpenPopupCreateCredential, handleToggleContextMenu } from '@/entrypoints/background/PopupMessageHandler';import { handleStoreSavePromptState, handleGetSavePromptState, handleClearSavePromptState, handleStoreLastAutofilled, handleGetLastAutofilled, handleClearLastAutofilled } from '@/entrypoints/background/SavePromptStateHandler';import { handleGetTwoFactorState, handleClearTwoFactorState } from '@/entrypoints/background/TwoFactorStateHandler';-import { handleCheckAuthStatus, handleClearPersistedFormValues, handleClearSession, handleClearVaultData, handleLockVault, handleGetFilteredItems, handleGetSearchItems, handleGetEncryptionKey, handleGetUnlockKeyDerivationParams, handleGetPersistedFormValues, handleGetVaultMigrationStatus, handlePersistFormValues, handleStoreUnlockKey, handleStoreUnlockKeyDerivationParams, handleStoreEncryptedVaultChunk, handleGetSyncState, handleMigrateVaultManifest, handleFullVaultSync, handleGroupCreateVault, handleGroupInviteMember, handleGroupUpdateVault, handleGroupRevokeAccess, handleCheckLoginDuplicate, handleSaveLoginCredential, handleAddUrlToCredential, handleIsUrlLinkedToCredential, handleGetLoginSaveSettings, handleGetItemsWithTotp, handleSearchItemsWithTotp, handleGetTotpSecrets, handleGenerateTotpCode, handleSetRecentlySelected, handleRecordItemUsage } from '@/entrypoints/background/VaultMessageHandler';+import { handleCheckAuthStatus, handleClearPersistedFormValues, handleClearSession, handleClearVaultData, handleLockVault, handleGetFilteredItems, handleGetSearchItems, handleGetEncryptionKey, handleGetUnlockKeyDerivationParams, handleGetPersistedFormValues, handleGetVaultMigrationStatus, handlePersistFormValues, handleStoreAccountKey, handleStoreUnlockKeyDerivationParams, handleStoreEncryptedVaultChunk, handleGetSyncState, handleMigrateVaultManifest, handleFullVaultSync, handleGroupCreateVault, handleGroupInviteMember, handleGroupUpdateVault, handleGroupRevokeAccess, handleCheckLoginDuplicate, handleSaveLoginCredential, handleAddUrlToCredential, handleIsUrlLinkedToCredential, handleGetLoginSaveSettings, handleGetItemsWithTotp, handleSearchItemsWithTotp, handleGetTotpSecrets, handleGenerateTotpCode, handleSetRecentlySelected, handleRecordItemUsage } from '@/entrypoints/background/VaultMessageHandler';import { logFailure } from '@/utils/Diagnostics';import { LocalPreferencesService } from '@/utils/LocalPreferencesService';@@ -252,10 +252,10 @@ export default defineBackground({onMessage('GET_FILTERED_ITEMS', ({ data }) => handleGetFilteredItems(data));onMessage('GET_SEARCH_ITEMS', ({ data }) => handleGetSearchItems(data));- onExtensionPageMessage('STORE_UNLOCK_KEY', async ({ data }) => {- const result = await handleStoreUnlockKey(data);+ onExtensionPageMessage('STORE_ACCOUNT_KEY', async ({ data }) => {+ const result = await handleStoreAccountKey(data);/*- * Storing the unlock key means the vault just became unlocked; let content scripts+ * Storing the Account Key means the vault just became unlocked; let content scripts* re-query any conditional passkey requests they parked while the vault was locked.*/if (result.success) {diff --git a/apps/browser-extension/src/entrypoints/background/AuthHandler.ts b/apps/browser-extension/src/entrypoints/background/AuthHandler.tsindex d4e3bdd7b..d8db48c06 100644--- a/apps/browser-extension/src/entrypoints/background/AuthHandler.ts+++ b/apps/browser-extension/src/entrypoints/background/AuthHandler.ts@@ -9,7 +9,7 @@ import { VaultKeyService } from '@aliasvault/client/auth/VaultKeyService';import { logoutReasonKey } from '@aliasvault/client/sync/VaultSync';import { handleClearTwoFactorState, handleGetTwoFactorState, handleStoreTwoFactorState } from '@/entrypoints/background/TwoFactorStateHandler';-import { handleClearSession, handleFullVaultSync, handleGetUnlockKeyDerivationParams, handleStoreUnlockKey, handleStoreUnlockKeyDerivationParams } from '@/entrypoints/background/VaultMessageHandler';+import { handleClearSession, handleFullVaultSync, handleGetUnlockKeyDerivationParams, handleStoreAccountKey, handleStoreUnlockKeyDerivationParams } from '@/entrypoints/background/VaultMessageHandler';import { StorageKeys } from '@/utils/constants/storageKeys';import { logExpected, logFailure } from '@/utils/Diagnostics';@@ -116,10 +116,10 @@ async function checkServerStatus(webApi: WebApiService): Promise<{ online: boole}/**- * Store the checked key (see VaultKeyService.SessionKeys.accountKey), which unlocks the vault, and tell content scripts about it.+ * Store the verified Account Key, which unlocks the vault, and tell content scripts about it.*/-async function storeUnlockKey(unlockKey: string, offline: boolean, broadcast: boolean): Promise<void> {- const stored = await handleStoreUnlockKey(unlockKey);+async function storeAccountKey(accountKey: string, offline: boolean, broadcast: boolean): Promise<void> {+ const stored = await handleStoreAccountKey(accountKey);if (!stored.success) {throw new Error(stored.error);}@@ -143,15 +143,15 @@ export function handleUnlockWithPassword(data: { password: string }): Promise<Ba}try {- let unlockKey: string;+ let accountKey: string;if (status.online) {const username = await storage.getItem<string>(StorageKeys.USERNAME);const loginResponse = await new SrpLoginService(webApi).initiateLogin(username!);- const credentials = await SrpAuthService.prepareCredentials(data.password, loginResponse.salt, loginResponse.encryptionType, loginResponse.encryptionSettings);+ const unlockKey = await SrpAuthService.deriveUnlockKey(data.password, loginResponse.salt, loginResponse.encryptionSettings);await handleStoreUnlockKeyDerivationParams({ salt: loginResponse.salt, encryptionType: loginResponse.encryptionType, encryptionSettings: loginResponse.encryptionSettings });// Throws an unlock-key-rejected (E-206) error on a wrong password.- unlockKey = await VaultKeyService.refreshKeyChain(credentials.passwordHashBase64, webApi);+ accountKey = await VaultKeyService.refreshKeyChain(unlockKey, webApi);} else {const storedParams = await handleGetUnlockKeyDerivationParams();if (!storedParams) {@@ -159,11 +159,11 @@ export function handleUnlockWithPassword(data: { password: string }): Promise<Bareturn { status: 'error', error: { key: 'common.errors.serverNotAvailable', wrongPassword: false } };}- const credentials = await SrpAuthService.prepareCredentials(data.password, storedParams.salt, storedParams.encryptionType, storedParams.encryptionSettings);- unlockKey = await VaultKeyService.verifyUnlockKey(credentials.passwordHashBase64);+ const unlockKey = await SrpAuthService.deriveUnlockKey(data.password, storedParams.salt, storedParams.encryptionSettings);+ accountKey = await VaultKeyService.verifyUnlockKey(unlockKey);}- await storeUnlockKey(unlockKey, !status.online, true);+ await storeAccountKey(accountKey, !status.online, true);await resetFailedAttempts();await LocalPreferencesService.resetPasswordUnlockFailedAttempts();await LocalPreferencesService.setLastUsedUnlockMethod('password');@@ -181,21 +181,21 @@ export function handleUnlockWithPassword(data: { password: string }): Promise<Ba}/**- * Unlock the vault with the PIN, which decrypts the stored unlock key.+ * Unlock the vault with the PIN, which decrypts the stored Account Key.*/export function handleUnlockWithPin(data: { pin: string }): Promise<BackgroundAuthResult> {return runExclusive(async () => {try {const pinKey = await unlockWithPin(data.pin);- const unlockKey = await VaultKeyService.verifyUnlockKey(pinKey);- await convertLegacyPinKey(data.pin, pinKey, unlockKey);+ const accountKey = await VaultKeyService.verifyUnlockKey(pinKey);+ await convertLegacyPinKey(data.pin, pinKey, accountKey);const status = await checkServerStatus(new WebApiService());if ('logout' in status) {return status.logout;}- await storeUnlockKey(unlockKey, !status.online, true);+ await storeAccountKey(accountKey, !status.online, true);await LocalPreferencesService.setLastUsedUnlockMethod('pin');return { status: 'success', offline: !status.online };} catch (err) {@@ -241,7 +241,7 @@ export function handleLoginWithPassword(data: { username: string; password: strireturn { status: 'error', error: { key: 'common.errors.unknownError', wrongPassword: false } };}- return await completeLogin(username, validation.token.token, validation.token.refreshToken, credentials.passwordHashBase64, loginResponse);+ return await completeLogin(username, validation.token.token, validation.token.refreshToken, credentials.unlockKeyBase64, loginResponse);} catch (err) {return failureResult('Login error', err);}@@ -266,7 +266,7 @@ export function handleLoginWithTwoFactor(data: { code: string }): Promise<Backgr}handleClearTwoFactorState();- return await completeLogin(state.username, validation.token.token, validation.token.refreshToken, state.credentials.passwordHashBase64, state.loginResponse);+ return await completeLogin(state.username, validation.token.token, validation.token.refreshToken, state.credentials.unlockKeyBase64, state.loginResponse);} catch (err) {return failureResult('2FA error', err);}@@ -283,9 +283,9 @@ 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();- let storedKey: string;+ let accountKey: string;try {- storedKey = await VaultKeyService.refreshKeyChain(unlockKey, webApi);+ accountKey = await VaultKeyService.refreshKeyChain(unlockKey, webApi);} catch (err) {await webApi.revokeTokens();await handleClearSession();@@ -295,7 +295,7 @@ async function completeLogin(username: string, token: string, refreshToken: striawait handleStoreUnlockKeyDerivationParams({ salt: derivationParams.salt, encryptionType: derivationParams.encryptionType, encryptionSettings: derivationParams.encryptionSettings });// Content scripts are told once the vault is pulled: before that there is nothing to autofill from.- await storeUnlockKey(storedKey, false, false);+ await storeAccountKey(accountKey, false, false);const sync = await handleFullVaultSync({ forcePull: true, reportErrorToPopup: false });if (sync.logoutReason === 'clientVersionNotSupported') {diff --git a/apps/browser-extension/src/entrypoints/background/AutolockTimeoutHandler.ts b/apps/browser-extension/src/entrypoints/background/AutolockTimeoutHandler.tsindex fcfa90fe9..7d14ac109 100644--- a/apps/browser-extension/src/entrypoints/background/AutolockTimeoutHandler.ts+++ b/apps/browser-extension/src/entrypoints/background/AutolockTimeoutHandler.ts@@ -26,8 +26,8 @@ let shortTimeoutTimer: ReturnType<typeof setTimeout> | null = null;*/async function lockVaultDueToInactivity(): Promise<void> {// Check if vault is still unlocked before locking- const unlockKey = await storage.getItem(StorageKeys.UNLOCK_KEY) as string | null;- if (!unlockKey) {+ const accountKey = await storage.getItem(StorageKeys.ACCOUNT_KEY) as string | null;+ if (!accountKey) {// Vault is already lockedreturn;}@@ -87,8 +87,8 @@ async function setAutoLockTimer(timeoutSeconds: number): Promise<void> {*/export async function initializeAutoLockAlarm(): Promise<void> {// Check if vault is unlocked- const unlockKey = await storage.getItem(StorageKeys.UNLOCK_KEY) as string | null;- if (!unlockKey) {+ const accountKey = await storage.getItem(StorageKeys.ACCOUNT_KEY) as string | null;+ if (!accountKey) {// Vault is locked, clear any existing alarmclearShortTimeoutTimer();await browser.alarms.clear(AUTO_LOCK_ALARM_NAME);@@ -151,8 +151,8 @@ export async function handleResetAutoLockTimer(): Promise<void> {}// Check if vault is unlocked before setting timer- const unlockKey = await storage.getItem(StorageKeys.UNLOCK_KEY) as string | null;- if (!unlockKey) {+ const accountKey = await storage.getItem(StorageKeys.ACCOUNT_KEY) as string | null;+ if (!accountKey) {// Vault is already locked, don't start timerclearShortTimeoutTimer();await browser.alarms.clear(AUTO_LOCK_ALARM_NAME);@@ -176,8 +176,8 @@ export async function handlePopupHeartbeat(): Promise<void> {}// Check if vault is unlocked- const unlockKey = await storage.getItem(StorageKeys.UNLOCK_KEY) as string | null;- if (!unlockKey) {+ const accountKey = await storage.getItem(StorageKeys.ACCOUNT_KEY) as string | null;+ if (!accountKey) {// Vault is already locked, don't extend timerreturn;}@@ -202,8 +202,8 @@ export async function handleSetAutoLockTimeout(timeout: number): Promise<boolean}// Check if vault is unlocked before setting new timer- const unlockKey = await storage.getItem(StorageKeys.UNLOCK_KEY) as string | null;- if (!unlockKey) {+ const accountKey = await storage.getItem(StorageKeys.ACCOUNT_KEY) as string | null;+ if (!accountKey) {// Vault is locked, don't start timerreturn true;}diff --git a/apps/browser-extension/src/entrypoints/background/VaultMessageHandler.ts b/apps/browser-extension/src/entrypoints/background/VaultMessageHandler.tsindex aab5b4a95..6a612cccf 100644--- a/apps/browser-extension/src/entrypoints/background/VaultMessageHandler.ts+++ b/apps/browser-extension/src/entrypoints/background/VaultMessageHandler.ts@@ -198,15 +198,15 @@ export async function handleCheckAuthStatus() : Promise<{ isLoggedIn: boolean, i* Store the session's key in session storage. It is the one secret the session holds: the vault encryption key and the* account private key are derived from it and the cached key chain on demand.*/-export async function handleStoreUnlockKey(- unlockKey: string,+export async function handleStoreAccountKey(+ accountKey: string,) : Promise<messageBoolResponse> {try {- await storage.setItem(StorageKeys.UNLOCK_KEY, unlockKey);+ await storage.setItem(StorageKeys.ACCOUNT_KEY, accountKey);return { success: true };} catch (error) {- logFailure('Failed to store unlock key', error);- // E-602: Storage write failed during unlock key store+ logFailure('Failed to store Account Key', error);+ // E-602: Storage write failed during Account Key storereturn { success: false, error: formatErrorWithCode(await t('common.errors.unknownErrorTryAgain'), AppErrorCode.STORAGE_WRITE_FAILED) };}}@@ -456,7 +456,7 @@ export async function handleGetPasswordSettings(}/**- * Get the encryption key for the encrypted vault: derived from the session unlock key and the cached key chain,+ * Get the encryption key for the encrypted vault: derived from the Account Key and the cached key chain,* null while the vault is locked.*/export async function handleGetEncryptionKey(diff --git a/apps/browser-extension/src/entrypoints/popup/context/DbContext.tsx b/apps/browser-extension/src/entrypoints/popup/context/DbContext.tsxindex fa84d6cfa..2ab4ee090 100644--- a/apps/browser-extension/src/entrypoints/popup/context/DbContext.tsx+++ b/apps/browser-extension/src/entrypoints/popup/context/DbContext.tsx@@ -12,7 +12,7 @@ import { StorageKeys } from '@/utils/constants/storageKeys';import { logFailure } from '@/utils/Diagnostics';import { onMessage, sendMessage } from '@/utils/messaging/ExtensionMessaging';-import { markOwnUnlockKey, vaultStateEvents } from '@/events/VaultStateEvents';+import { markOwnAccountKey, vaultStateEvents } from '@/events/VaultStateEvents';import { t } from '@/i18n/StandaloneI18n';import type { SyncErrorDetail } from '@aliasvault/client/sync/VaultSync';@@ -91,7 +91,7 @@ type DbContextType = {* Returns the SqliteClient if vault was loaded successfully, null otherwise.*/loadStoredDatabase: () => Promise<SqliteClient | null>;- storeUnlockKey: (unlockKey: string) => Promise<void>;+ storeAccountKey: (accountKey: string) => Promise<void>;storeUnlockKeyDerivationParams: (params: UnlockKeyDerivationParams) => Promise<void>;clearDatabase: () => void;getVaultMetadata: () => Promise<VaultMetadata | null>;@@ -375,13 +375,13 @@ export const DbProvider: React.FC<{ children: React.ReactNode }> = ({ children }* Store the session's key in the background worker. It is the one secret the session holds; the vault encryption key* is derived from it and the cached key chain.*/- const storeUnlockKey = useCallback(async (unlockKey: string) : Promise<void> => {+ const storeAccountKey = useCallback(async (accountKey: string) : Promise<void> => {/** Mark as our own write BEFORE sending, so the cross-window watcher* ignores the storage event triggered by this same flow.*/- markOwnUnlockKey(unlockKey);- await sendMessage('STORE_UNLOCK_KEY', unlockKey);+ markOwnAccountKey(accountKey);+ await sendMessage('STORE_ACCOUNT_KEY', accountKey);}, []);/**@@ -420,7 +420,7 @@ export const DbProvider: React.FC<{ children: React.ReactNode }> = ({ children }setIsUploading,shouldSuppressEmailErrors,loadStoredDatabase,- storeUnlockKey,+ storeAccountKey,storeUnlockKeyDerivationParams,clearDatabase,getVaultMetadata,@@ -429,7 +429,7 @@ export const DbProvider: React.FC<{ children: React.ReactNode }> = ({ children }requiresManifestMigration,syncError,clearSyncError,- }), [sqliteClient, dbInitialized, dbAvailable, isOffline, getIsOffline, hasUnsyncedUserChanges, isSyncing, isUploading, setIsOffline, shouldSuppressEmailErrors, loadStoredDatabase, storeUnlockKey, storeUnlockKeyDerivationParams, clearDatabase, getVaultMetadata, refreshSyncState, requiresLegacySqliteBlobMigration, requiresManifestMigration, syncError, clearSyncError]);+ }), [sqliteClient, dbInitialized, dbAvailable, isOffline, getIsOffline, hasUnsyncedUserChanges, isSyncing, isUploading, setIsOffline, shouldSuppressEmailErrors, loadStoredDatabase, storeAccountKey, storeUnlockKeyDerivationParams, clearDatabase, getVaultMetadata, refreshSyncState, requiresLegacySqliteBlobMigration, requiresManifestMigration, syncError, clearSyncError]);return (<DbContext.Provider value={contextValue}>diff --git a/apps/browser-extension/src/entrypoints/popup/pages/auth/Login.tsx b/apps/browser-extension/src/entrypoints/popup/pages/auth/Login.tsxindex 42a712ca1..0e2315860 100644--- a/apps/browser-extension/src/entrypoints/popup/pages/auth/Login.tsx+++ b/apps/browser-extension/src/entrypoints/popup/pages/auth/Login.tsx@@ -167,7 +167,7 @@ const Login: React.FC = () => {* @param username - the normalized username* @param token - the access token* @param refreshToken - the refresh token- * @param unlockKey - the key the phone sent (its stored key), base64+ * @param unlockKey - the key the phone sent (its Account Key, or an unlock key from an older app), base64* @param derivationParams - how the unlock key is derived from the password*/const handleSuccessfulAuth = async (@@ -184,9 +184,9 @@ const Login: React.FC = () => {* Fetch the account's key chain, check the unlock key opens it and cache it as-is; the vault encryption key is* derived from the two on demand. Legacy accounts have no chain.*/- let storedKey: string;+ let accountKey: string;try {- storedKey = 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();@@ -199,8 +199,8 @@ const Login: React.FC = () => {encryptionSettings: derivationParams.encryptionSettings});- // Store the session key, then pull and load the vault.- await dbContext.storeUnlockKey(storedKey);+ // Store the Account Key, then pull and load the vault.+ await dbContext.storeAccountKey(accountKey);await pullAndLoadVault();// Reset prefill flag so next logout will prefill againdiff --git a/apps/browser-extension/src/entrypoints/popup/pages/auth/Unlock.tsx b/apps/browser-extension/src/entrypoints/popup/pages/auth/Unlock.tsxindex 21f8b1e08..45b04a603 100644--- a/apps/browser-extension/src/entrypoints/popup/pages/auth/Unlock.tsx+++ b/apps/browser-extension/src/entrypoints/popup/pages/auth/Unlock.tsx@@ -460,10 +460,10 @@ const Unlock: React.FC = () => {await authContext.setAuthTokens(result.username, result.token, result.refreshToken);// The mobile device sends its stored key.- const storedKey = await VaultKeyService.refreshKeyChain(result.unlockKey, webApi);+ const accountKey = await VaultKeyService.refreshKeyChain(result.unlockKey, webApi);- // Store the session key and derivation params- await dbContext.storeUnlockKey(storedKey);+ // Store the Account Key and derivation params+ await dbContext.storeAccountKey(accountKey);await dbContext.storeUnlockKeyDerivationParams({salt: result.salt,encryptionType: result.encryptionType,diff --git a/apps/browser-extension/src/entrypoints/popup/pages/settings/VaultUnlockSettings.tsx b/apps/browser-extension/src/entrypoints/popup/pages/settings/VaultUnlockSettings.tsxindex f819f8c09..4f8bbecd6 100644--- a/apps/browser-extension/src/entrypoints/popup/pages/settings/VaultUnlockSettings.tsx+++ b/apps/browser-extension/src/entrypoints/popup/pages/settings/VaultUnlockSettings.tsx@@ -128,16 +128,16 @@ const VaultUnlockSettings: React.FC = () => {try {showLoading();- const unlockKey = await VaultKeyService.getSessionUnlockKey();+ const accountKey = await VaultKeyService.getSessionAccountKey();- if (!unlockKey) {+ if (!accountKey) {setError(t('common.errors.unknownErrorTryAgain'));hideLoading();return;}/* Setup PIN with the unlock key */- await setupPin(newPin, unlockKey);+ await setupPin(newPin, accountKey);/** Mark PIN as the last-used unlock method so the unlock screen defaults todiff --git a/apps/browser-extension/src/events/VaultStateEvents.ts b/apps/browser-extension/src/events/VaultStateEvents.tsindex badef4053..56fed2f33 100644--- a/apps/browser-extension/src/events/VaultStateEvents.ts+++ b/apps/browser-extension/src/events/VaultStateEvents.ts@@ -10,26 +10,26 @@ type Listener = () => void;* storage events. Reset to null whenever the key is removed (any lock), so a* subsequent unlock in another window is detected as a foreign write.*/-let lastOwnUnlockKey: string | null = null;+let lastOwnAccountKey: string | null = null;/*** Record an unlock-key value that THIS window is about to write. Must be* called BEFORE the actual write so the storage watcher can skip the* resulting self-event. The popup unlock/login flows call this via- * `DbContext.storeUnlockKey`.+ * `DbContext.storeAccountKey`.*/-export function markOwnUnlockKey(key: string): void {- lastOwnUnlockKey = key;+export function markOwnAccountKey(key: string): void {+ lastOwnAccountKey = key;}/*- * Reset `lastOwnUnlockKey` whenever the key is cleared in storage (i.e.+ * Reset `lastOwnAccountKey` whenever the key is cleared in storage (i.e.* any window locks/logs out). Without this, A's stored "own" value would* mask a later unlock from B that happens to use the same key value.*/-storage.watch<string | null>(StorageKeys.UNLOCK_KEY, (newValue) => {+storage.watch<string | null>(StorageKeys.ACCOUNT_KEY, (newValue) => {if (!newValue) {- lastOwnUnlockKey = null;+ lastOwnAccountKey = null;}});@@ -39,7 +39,7 @@ storage.watch<string | null>(StorageKeys.UNLOCK_KEY, (newValue) => {export const vaultStateEvents = {/** Fires when the vault is locked in any window. */onVaultLocked(listener: Listener): Unsubscribe {- return storage.watch<string | null>(StorageKeys.UNLOCK_KEY, (newValue) => {+ return storage.watch<string | null>(StorageKeys.ACCOUNT_KEY, (newValue) => {if (!newValue) {listener();}@@ -48,8 +48,8 @@ export const vaultStateEvents = {/*** Fires when ANOTHER window unlocks the vault (or completes login). The- * active window's own write is filtered via `lastOwnUnlockKey`, which- * is set synchronously before the write through `markOwnUnlockKey`.+ * active window's own write is filtered via `lastOwnAccountKey`, which+ * is set synchronously before the write through `markOwnAccountKey`.** Unlocked means a foreign key AND a stored vault: a login stores its key* before the vault pull lands, so the key alone is not yet a vault to open.@@ -60,16 +60,16 @@ export const vaultStateEvents = {*/const fireIfUnlocked = async (): Promise<void> => {const [key, vault] = await Promise.all([- storage.getItem<string | null>(StorageKeys.UNLOCK_KEY),+ storage.getItem<string | null>(StorageKeys.ACCOUNT_KEY),storage.getItem<string | null>(StorageKeys.ENCRYPTED_VAULT),]);- if (key && vault && key !== lastOwnUnlockKey) {+ if (key && vault && key !== lastOwnAccountKey) {listener();}};- const unwatchKey = storage.watch<string | null>(StorageKeys.UNLOCK_KEY, (newValue) => {- if (newValue && newValue !== lastOwnUnlockKey) {+ const unwatchKey = storage.watch<string | null>(StorageKeys.ACCOUNT_KEY, (newValue) => {+ if (newValue && newValue !== lastOwnAccountKey) {void fireIfUnlocked();}});diff --git a/apps/browser-extension/src/utils/LegacyKeyConversion.ts b/apps/browser-extension/src/utils/LegacyKeyConversion.tsindex b45024456..ded3d4ef6 100644--- a/apps/browser-extension/src/utils/LegacyKeyConversion.ts+++ b/apps/browser-extension/src/utils/LegacyKeyConversion.ts@@ -5,7 +5,7 @@ import { setupPin } from '@/utils/PinUnlockService';** 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`.+ * with the Account Key, once. The stored Account Key itself converts in core/client `convertLegacySessionKey`.** TODO: remove once accounts without a key chain (pre-0.31.0) are no longer supported.*/diff --git a/apps/browser-extension/src/utils/PinUnlockService.ts b/apps/browser-extension/src/utils/PinUnlockService.tsindex 758188b21..c0088c750 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 session's stored key (the Account Key)+ * of entering their full master password. The Account Key* is encrypted with a key derived from the PIN and stored locally.** Security features:@@ -147,12 +147,12 @@ export async function isPinLocked(): Promise<boolean> {/*** Setup PIN unlock- * Encrypts the unlock key with the PIN and stores it+ * Encrypts the session's Account Key with the PIN and stores it** @param pin - The PIN to set (6-8 digits)- * @param unlockKey - The base64-encoded stored key to protect (VaultKeyService.getSessionUnlockKey)+ * @param accountKey - The base64 Account Key to protect (VaultKeyService.getSessionAccountKey)*/-export async function setupPin(pin: string, unlockKey: string): Promise<void> {+export async function setupPin(pin: string, accountKey: string): Promise<void> {if (!isValidPin(pin)) {throw new InvalidPinFormatError();}@@ -166,12 +166,12 @@ export async function setupPin(pin: string, unlockKey: string): Promise<void> {const combinedSalt = await assembleSaltWithPepper(salt);const pinKey = await derivePinKey(pin, combinedSalt);- // Encrypt the unlock key+ // Encrypt the Account Keyconst iv = crypto.getRandomValues(new Uint8Array(12));const encryptedKey = await crypto.subtle.encrypt({ name: 'AES-GCM', iv },pinKey,- new TextEncoder().encode(unlockKey)+ new TextEncoder().encode(accountKey));// Combine IV + encrypted data@@ -238,7 +238,7 @@ export async function unlockWithPin(pin: string): Promise<string> {const combinedSalt = await assembleSaltWithPepper(salt);const pinKey = await derivePinKey(pin, combinedSalt);- // Decrypt the unlock key+ // Decrypt the stored keyconst decryptedData = await crypto.subtle.decrypt({ name: 'AES-GCM', iv },pinKey,diff --git a/apps/browser-extension/src/utils/messaging/ExtensionMessaging.ts b/apps/browser-extension/src/utils/messaging/ExtensionMessaging.tsindex aab7c986b..2ffb384f6 100644--- a/apps/browser-extension/src/utils/messaging/ExtensionMessaging.ts+++ b/apps/browser-extension/src/utils/messaging/ExtensionMessaging.ts@@ -114,7 +114,7 @@ export interface IExtensionMessageProtocol {SET_RECENTLY_SELECTED(data: { itemId: string; manifestId: string; domain: string }): { success: boolean };START_VAULT_SYNC(): BoolResponse;STORE_ENCRYPTED_VAULT(data: { transferId: string; index: number; chunk: string; commit?: VaultBlobStoreOptions }): { success: boolean; mutationSequence: number } | null;- STORE_UNLOCK_KEY(data: string): BoolResponse;+ STORE_ACCOUNT_KEY(data: string): BoolResponse;STORE_UNLOCK_KEY_DERIVATION_PARAMS(data: UnlockKeyDerivationParams): BoolResponse;STORE_LAST_AUTOFILLED(data: LastAutofilledCredential): { success: boolean };STORE_SAVE_PROMPT_STATE(data: SavePromptPersistedState): { success: boolean };diff --git a/apps/browser-extension/tests/helpers/test-api.ts b/apps/browser-extension/tests/helpers/test-api.tsindex b1b674c3a..8e3d51f21 100644--- a/apps/browser-extension/tests/helpers/test-api.ts+++ b/apps/browser-extension/tests/helpers/test-api.ts@@ -28,7 +28,7 @@ export type TestUser = {token?: TokenModel;/** TOTP secret if 2FA is enabled */totpSecret?: string;- /** Argon2Id password-derived key (the KEK), for tests that walk the account key chain API-side. */+ /** The Argon2Id unlock key, for tests that walk the account key chain API-side. */encryptionKey?: Uint8Array;};@@ -59,7 +59,7 @@ export function generateTestPassword(): string {* @param apiBaseUrl - The base URL of the API (e.g., 'http://localhost:5100')* @param username - The username for the new account* @param password - The password for the new account- * @returns The token model and the password-derived key (KEK) on success+ * @returns The token model and the unlock key on success* @throws Error if registration fails*/export async function registerTestUser(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 edc114a27..99dffb486 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@@ -126,7 +126,7 @@ class MainActivity : ReactActivity() {* Handle PIN unlock result directly without going through React context.* This avoids race conditions with React context initialization.* @param resultCode The result code from the PIN unlock activity.- * @param data The intent data containing the unlock key.+ * @param data The intent data containing the Account Key.*/private fun handlePinUnlockResult(resultCode: Int, data: Intent?) {val promise = net.aliasvault.app.nativevaultmanager.NativeVaultManager.pendingActivityResultPromise@@ -147,12 +147,12 @@ class MainActivity : ReactActivity() {net.aliasvault.app.pinunlock.PinUnlockActivity.RESULT_SUCCESS -> {// Clear auth context on successnet.aliasvault.app.nativevaultmanager.NativeVaultManager.pendingAuthContext = null- val unlockKeyBase64 = data?.getStringExtra(- net.aliasvault.app.pinunlock.PinUnlockActivity.EXTRA_UNLOCK_KEY,+ val accountKeyBase64 = data?.getStringExtra(+ net.aliasvault.app.pinunlock.PinUnlockActivity.EXTRA_ACCOUNT_KEY,)- if (unlockKeyBase64 == null) {- promise.reject("UNLOCK_ERROR", "Failed to get unlock key from PIN unlock", null)+ if (accountKeyBase64 == null) {+ promise.reject("UNLOCK_ERROR", "Failed to get Account Key from PIN unlock", null)return}@@ -161,12 +161,12 @@ class MainActivity : ReactActivity() {CoroutineScope(Dispatchers.IO).launch {try {/*- * Use storeUnlockKeyInMemory instead of storeUnlockKey.- * storeUnlockKey would trigger biometric prompt if biometrics is enabled+ * Use storeAccountKeyInMemory instead of storeAccountKey.+ * storeAccountKey would trigger biometric prompt if biometrics is enabled* since it tries to store the key in the biometric-protected keystore.* For PIN unlock, we just want to set the key in memory.*/- vaultStore.storeUnlockKeyInMemory(unlockKeyBase64)+ vaultStore.storeAccountKeyInMemory(accountKeyBase64)vaultStore.unlockVault()promise.resolve(true)} catch (e: Exception) {@@ -270,7 +270,7 @@ class MainActivity : ReactActivity() {kotlinx.coroutines.CoroutineScope(kotlinx.coroutines.Dispatchers.IO).launch {try {// Store unlock key in memory only- vaultStore.storeUnlockKeyInMemory(unlockKeyBase64)+ vaultStore.storeAccountKeyInMemory(unlockKeyBase64)// 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 5ef093f9a..0a3565aa9 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@@ -105,7 +105,7 @@ class UnlockCoordinator(override fun onSuccess(result: String) {try {// Biometric authentication successful, unlock vault- vaultStore.storeUnlockKeyInMemory(result)+ vaultStore.storeAccountKeyInMemory(result)vaultStore.unlockVault()// Notify success@@ -121,7 +121,7 @@ class UnlockCoordinator(}override fun onError(e: Exception) {- Log.e(TAG, "Failed to retrieve unlock key", e)+ Log.e(TAG, "Failed to retrieve Account Key", e)activity.runOnUiThread {handleBiometricKeystoreError(e)}@@ -136,11 +136,11 @@ class UnlockCoordinator(fun handlePinUnlockResult(resultCode: Int, data: Intent?) {when (resultCode) {PinUnlockActivity.RESULT_SUCCESS -> {- // PIN unlock successful - get unlock key and unlock vault- val unlockKey = data?.getStringExtra(PinUnlockActivity.EXTRA_UNLOCK_KEY)- if (unlockKey != null) {+ // PIN unlock successful - get Account Key and unlock vault+ val accountKey = data?.getStringExtra(PinUnlockActivity.EXTRA_ACCOUNT_KEY)+ if (accountKey != null) {try {- vaultStore.storeUnlockKeyInMemory(unlockKey)+ vaultStore.storeAccountKeyInMemory(accountKey)vaultStore.unlockVault()onUnlocked()} catch (e: Exception) {@@ -148,7 +148,7 @@ class UnlockCoordinator(onError(getUnlockErrorMessage(e))}} else {- Log.e(TAG, "No unlock key returned from PIN unlock")+ Log.e(TAG, "No Account Key returned from PIN unlock")onError("Failed to unlock vault")}}@@ -180,7 +180,7 @@ class UnlockCoordinator(val unlockKey = data?.getStringExtra(PasswordUnlockActivity.EXTRA_UNLOCK_KEY)if (unlockKey != null) {try {- vaultStore.storeUnlockKeyInMemory(unlockKey)+ vaultStore.storeAccountKeyInMemory(unlockKey)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 353830602..017e8eed8 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@@ -242,35 +242,35 @@ class NativeVaultManager(reactContext: ReactApplicationContext) :}/**- * Open a session in memory with the unlock key, without keystore persistence.+ * 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 base64UnlockKey The unlock key as a base64 encoded string+ * @param base64Key The unlock key or Account Key as a base64 encoded string* @param promise The promise to resolve*/@ReactMethod- override fun storeUnlockKeyInMemory(base64UnlockKey: String, promise: Promise) {+ override fun storeAccountKeyInMemory(base64Key: String, promise: Promise) {try {- vaultStore.storeUnlockKeyInMemory(base64UnlockKey)+ vaultStore.storeAccountKeyInMemory(base64Key)promise.resolve(null)} catch (e: Exception) {- Log.e(TAG, "Error storing unlock key in memory", e)- promise.reject("ERR_STORE_KEY_MEMORY", "Failed to store unlock key in memory: ${e.message}", e)+ 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 AND persist it to keystore (may trigger biometric prompt).- * @param base64UnlockKey The unlock key as a base64 encoded string+ * 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 storeUnlockKey(base64UnlockKey: String, promise: Promise) {+ override fun storeAccountKey(base64Key: String, promise: Promise) {try {- vaultStore.storeUnlockKey(base64UnlockKey)+ vaultStore.storeAccountKey(base64Key)promise.resolve(null)} catch (e: Exception) {- Log.e(TAG, "Error storing unlock key", e)- promise.reject("ERR_STORE_KEY", "Failed to store unlock key: ${e.message}", e)+ Log.e(TAG, "Error storing Account Key", e)+ promise.reject("ERR_STORE_KEY", "Failed to store Account Key: ${e.message}", e)}}@@ -345,7 +345,7 @@ class NativeVaultManager(reactContext: ReactApplicationContext) :/*** Resolve and store the vault key right after login from the unlock key (see VaultStore.resolveVaultKey).- * Resolves with the stored key; rejects with the native error code when the chain does not open or the session is gone.+ * Resolves with the vault key; rejects with the native error code when the chain does not open or the session is gone.* @param base64DerivedKey The password-derived key as base64* @param promise The promise to resolve*/@@ -378,14 +378,14 @@ class NativeVaultManager(reactContext: ReactApplicationContext) :}/**- * Encrypt the decryption key for mobile login.+ * Encrypt the Account Key for mobile login.* @param publicKeyJWK The public key in JWK format* @param promise The promise to resolve*/@ReactMethod- override fun encryptUnlockKeyForMobileLogin(publicKeyJWK: String, promise: Promise) {+ override fun encryptAccountKeyForMobileLogin(publicKeyJWK: String, promise: Promise) {try {- val encryptedKey = vaultStore.encryptUnlockKeyForMobileLogin(publicKeyJWK)+ val encryptedKey = vaultStore.encryptAccountKeyForMobileLogin(publicKeyJWK)promise.resolve(encryptedKey)} catch (e: Exception) {Log.e(TAG, "Error encrypting key for mobile login", e)@@ -1643,15 +1643,14 @@ class NativeVaultManager(reactContext: ReactApplicationContext) :/*** Show native PIN setup UI.* Launches the native PinUnlockActivity in setup mode.- * Gets the unlock key from memory (vault must be unlocked): the PIN protects that+ * Gets the Account Key from memory (vault must be unlocked): the PIN protects that* key, never the vault key.* @param promise The promise to resolve when setup completes or rejects if cancelled/error.*/@ReactMethodoverride fun showPinSetup(promise: Promise) {- // Get the unlock key first- vaultStore.getUnlockKey(object : net.aliasvault.app.vaultstore.interfaces.CryptoOperationCallback {- override fun onSuccess(unlockKey: String) {+ vaultStore.getAccountKey(object : net.aliasvault.app.vaultstore.interfaces.CryptoOperationCallback {+ override fun onSuccess(accountKey: String) {try {val activity = currentActivityif (activity == null) {@@ -1665,7 +1664,7 @@ class NativeVaultManager(reactContext: ReactApplicationContext) :// Launch PIN setup activityval intent = android.content.Intent(activity, net.aliasvault.app.pinunlock.PinUnlockActivity::class.java)intent.putExtra(net.aliasvault.app.pinunlock.PinUnlockActivity.EXTRA_MODE, net.aliasvault.app.pinunlock.PinUnlockActivity.MODE_SETUP)- intent.putExtra(net.aliasvault.app.pinunlock.PinUnlockActivity.EXTRA_SETUP_UNLOCK_KEY, unlockKey)+ intent.putExtra(net.aliasvault.app.pinunlock.PinUnlockActivity.EXTRA_SETUP_ACCOUNT_KEY, accountKey)activity.startActivityForResult(intent, PIN_SETUP_REQUEST_CODE)} catch (e: Exception) {@@ -1675,8 +1674,8 @@ class NativeVaultManager(reactContext: ReactApplicationContext) :}override fun onError(error: Exception) {- Log.e(TAG, "Error getting unlock key for PIN setup", error)- promise.reject("ERR_SETUP_PIN", "Failed to get unlock key: ${error.message}", error)+ Log.e(TAG, "Error getting Account Key for PIN setup", error)+ promise.reject("ERR_SETUP_PIN", "Failed to get Account Key: ${error.message}", error)}})}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 ec28afe4a..806d99637 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@@ -140,10 +140,10 @@ object RustCoreDispatcher {/** Open a key chain 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(storedKey: ByteArray, encryptedAccountKey: String, encryptedVek: String, encryptedAccountPrivateKey: String?): String {+ private fun openKeyChain(key: ByteArray, encryptedAccountKey: String, encryptedVek: String, encryptedAccountPrivateKey: String?): String {val result = JSONObject()try {- val keys = openAccountKeyChain(storedKey, encryptedAccountKey, encryptedVek, encryptedAccountPrivateKey)+ val keys = openAccountKeyChain(key, encryptedAccountKey, encryptedVek, encryptedAccountPrivateKey)result.put("status", "opened").put("vaultEncryptionKey", Base64.encodeToString(keys.vaultEncryptionKey, Base64.NO_WRAP)).put("accountKey", Base64.encodeToString(keys.accountKey, Base64.NO_WRAP))diff --git a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/pinunlock/PinState.kt b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/pinunlock/PinState.ktindex c38d0606e..2ad060c11 100644--- a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/pinunlock/PinState.kt+++ b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/pinunlock/PinState.kt@@ -46,9 +46,9 @@ enum class PinSetupStep {sealed class PinResult {/*** PIN processing succeeded.- * @property unlockKey The unlock key (returned for unlock mode, null for setup mode).+ * @property accountKey The Account Key (returned for unlock mode, null for setup mode).*/- data class Success(val unlockKey: String?) : PinResult()+ data class Success(val accountKey: String?) : PinResult()/*** PIN processing failed with an error.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 f43335e2d..101ca80e5 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@@ -44,7 +44,7 @@ import net.aliasvault.app.vaultstore.VaultStore* // Setup mode* val intent = Intent(context, PinUnlockActivity::class.java)* intent.putExtra(PinUnlockActivity.EXTRA_MODE, PinUnlockActivity.MODE_SETUP)- * intent.putExtra(PinUnlockActivity.EXTRA_SETUP_UNLOCK_KEY, unlockKey)+ * intent.putExtra(PinUnlockActivity.EXTRA_SETUP_ACCOUNT_KEY, accountKey)* startActivityForResult(intent, REQUEST_CODE)* ```*/@@ -60,14 +60,14 @@ class PinUnlockActivity : AppCompatActivity() {/** Result code when PIN was disabled due to max attempts. */const val RESULT_PIN_DISABLED = 100- /** 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 Account Key (returned in unlock mode). */+ const val EXTRA_ACCOUNT_KEY = "unlock_key"/** Intent extra key for the mode (unlock or setup). */const val EXTRA_MODE = "mode"- /** 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 the Account Key the PIN protects during setup. */+ const val EXTRA_SETUP_ACCOUNT_KEY = "setup_unlock_key"/** Intent extra key for custom title (optional). */const val EXTRA_CUSTOM_TITLE = "custom_title"@@ -97,7 +97,7 @@ class PinUnlockActivity : AppCompatActivity() {// Stateprivate var configuration: PinConfiguration? = null- private var setupUnlockKey: String? = null+ private var setupAccountKey: String? = nullprivate var currentPin: String = ""private var isProcessing: Boolean = false@@ -118,12 +118,12 @@ class PinUnlockActivity : AppCompatActivity() {)viewModel = PinViewModel(this, vaultStore)- // Get mode and unlock key from intent+ // Get mode and Account Key from intentval mode = when (intent.getStringExtra(EXTRA_MODE)) {MODE_SETUP -> PinMode.SETUPelse -> PinMode.UNLOCK}- setupUnlockKey = intent.getStringExtra(EXTRA_SETUP_UNLOCK_KEY)+ setupAccountKey = intent.getStringExtra(EXTRA_SETUP_ACCOUNT_KEY)val customTitle = intent.getStringExtra(EXTRA_CUSTOM_TITLE)val customSubtitle = intent.getStringExtra(EXTRA_CUSTOM_SUBTITLE)@@ -427,7 +427,7 @@ class PinUnlockActivity : AppCompatActivity() {delay(50)// Process the PIN- val result = viewModel.processPin(currentPin, config, setupUnlockKey)+ val result = viewModel.processPin(currentPin, config, setupAccountKey)// Handle resulthandlePinResult(result)@@ -451,8 +451,8 @@ class PinUnlockActivity : AppCompatActivity() {// Success - return resultval resultIntent = Intent()- result.unlockKey?.let {- resultIntent.putExtra(EXTRA_UNLOCK_KEY, it)+ result.accountKey?.let {+ resultIntent.putExtra(EXTRA_ACCOUNT_KEY, it)}setResult(RESULT_SUCCESS, resultIntent)finish()diff --git a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/pinunlock/PinViewModel.kt b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/pinunlock/PinViewModel.ktindex 1a1de9444..a0cfc7c1d 100644--- a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/pinunlock/PinViewModel.kt+++ b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/pinunlock/PinViewModel.kt@@ -54,11 +54,11 @@ class PinViewModel(suspend fun processPin(pin: String,configuration: PinConfiguration,- setupUnlockKey: String? = null,+ setupAccountKey: String? = null,): PinResult = withContext(Dispatchers.IO) {return@withContext when (configuration.mode) {PinMode.UNLOCK -> processUnlock(pin)- PinMode.SETUP -> processSetup(pin, configuration, setupUnlockKey)+ PinMode.SETUP -> processSetup(pin, configuration, setupAccountKey)}}@@ -67,8 +67,8 @@ class PinViewModel(*/private fun processUnlock(pin: String): PinResult {return try {- val unlockKey = vaultStore.unlockWithPin(pin)- PinResult.Success(unlockKey)+ val accountKey = vaultStore.unlockWithPin(pin)+ PinResult.Success(accountKey)} catch (e: PinUnlockException) {when (e) {is PinUnlockException.Locked -> {@@ -95,7 +95,7 @@ class PinViewModel(private fun processSetup(pin: String,configuration: PinConfiguration,- setupUnlockKey: String?,+ setupAccountKey: String?,): PinResult {return when (configuration.setupStep) {PinSetupStep.ENTER_NEW -> {@@ -131,13 +131,13 @@ class PinViewModel(// Setup the PINtry {- if (setupUnlockKey == null) {+ if (setupAccountKey == null) {return PinResult.Error(- "Unlock key required for PIN setup",+ "Account Key required for PIN setup",shouldClear = false,)}- vaultStore.setupPin(pin, setupUnlockKey)+ vaultStore.setupPin(pin, setupAccountKey)PinResult.Success(null)} catch (e: Exception) {PinResult.Error(diff --git a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/AppError.kt b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/AppError.ktindex 9d7ddeb26..de50addd4 100644--- a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/AppError.kt+++ b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/AppError.kt@@ -123,7 +123,7 @@ sealed class AppError(message: String, cause: Throwable? = null) : Exception(mes// Decryption errors/**- * Error indicating the locally stored vault does not decrypt with the session key.+ * Error indicating the locally stored vault does not decrypt with the Account Key.*/class VaultDecryptFailed(message: String = "Failed to decrypt vault",@@ -147,7 +147,7 @@ sealed class AppError(message: String, cause: Throwable? = null) : Exception(mes) : AppError("The account key does not open the vault encryption key: $message", cause)/**- * Error indicating the session key does not open the key chain the server holds; only a re-login recovers.+ * Error indicating the Account Key does not open the key chain the server holds; only a re-login recovers.*/class KeyOutOfSync(message: String = "Vault encryption key out of sync with the server; log in again",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 493086cc5..93a0306d7 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@@ -8,9 +8,10 @@ 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.+ * 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.** TODO: remove once accounts without a key chain (pre-0.31.0) are no longer supported.*/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 974b9cea3..f07741bb0 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@@ -74,33 +74,30 @@ class VaultCrypto(}/**- * The stored key: the one secret the unlocked session holds in memory, and the key the unlock methods (keystore,- * PIN) protect. Every other key is derived from it and the cached account key chain.+ * The Account Key the unlocked session holds and the keystore and PIN protect (see [LegacyKeyConversion]).*/- internal var unlockKey: ByteArray? = null+ internal var accountKey: ByteArray? = null/**- * The encryption key for the vault, derived from the unlock key. Null while the vault is locked.+ * The encryption key for the vault, derived from the Account Key. Null while the vault is locked.*/internal val encryptionKey: ByteArray?get() = sessionKeys()?.vaultEncryptionKey/**- * The account private key (JWK) of the unlocked session, derived from the unlock key.+ * The account private key (JWK) of the unlocked session, derived from the Account Key.*/internal val accountPrivateKey: String?get() = sessionKeys()?.accountPrivateKey/**- * What the stored key opens in the cached account key chain. A session that still holds an unlock key while the- * account has a chain (a sync accepted one created on another device) keeps the Account Key from now on; the- * keystore copy converts at the next biometric unlock (see [LegacyKeyConversion]), so this never prompts.+ * What the Account Key opens in the cached account key chain; a legacy key converts (see [LegacyKeyConversion]).*/@Suppress("SwallowedException")private fun sessionKeys(): SessionKeys? {- val key = unlockKey ?: return null+ val key = accountKey ?: return nullreturn try {- openAccountKeyChain(key).also { if (!it.accountKey.contentEquals(key)) unlockKey = it.accountKey }+ openAccountKeyChain(key).also { if (!it.accountKey.contentEquals(key)) accountKey = it.accountKey }} catch (e: Exception) {null}@@ -128,7 +125,7 @@ class VaultCrypto(// region Encryption Key Management/**- * Open a session with the unlock key and optionally persist that key to keystore if+ * 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.@@ -136,8 +133,8 @@ class VaultCrypto(* the key will only be stored in memory. It will be persisted to keystore on next unlock* when Activity context is available.*/- fun storeUnlockKey(base64UnlockKey: String, authMethods: String) {- openSession(Base64.decode(base64UnlockKey, Base64.NO_WRAP))+ fun storeAccountKey(base64Key: String, authMethods: String) {+ openSession(Base64.decode(base64Key, Base64.NO_WRAP))if (authMethods.contains(BIOMETRICS_AUTH_METHOD)) {try {@@ -145,7 +142,7 @@ class VaultCrypto(var error: Exception? = nullkeystoreProvider.storeKey(- key = Base64.encodeToString(unlockKey, Base64.NO_WRAP),+ key = Base64.encodeToString(accountKey, Base64.NO_WRAP),object : KeystoreOperationCallback {override fun onSuccess(result: String) {Log.d(TAG, "Encryption key stored successfully with biometric protection")@@ -175,15 +172,15 @@ class VaultCrypto(}/**- * Open a session in memory only with the unlock key.+ * Open a session in memory only with the unlock key or the Account Key.*/- fun storeUnlockKeyInMemory(base64UnlockKey: String) {- openSession(Base64.decode(base64UnlockKey, Base64.NO_WRAP))+ fun storeAccountKeyInMemory(base64Key: String) {+ openSession(Base64.decode(base64Key, Base64.NO_WRAP))}/**- * Clear the unlock key from memory.- * This forces getEncryptionKey() to fetch the unlock key from keystore on next biometric access.+ * Clear the Account Key from memory.+ * This forces getEncryptionKey() to fetch the Account Key from keystore on next biometric access.*/fun clearEncryptionKeyFromMemory() {clearKey()@@ -219,37 +216,28 @@ class VaultCrypto(return storageProvider.getAccountKeyChain()}- /*- * The stored key is the one secret a session holds; keystore and PIN only protect that same key. It is the Account- * Key, so it does not depend on the password: a typed password yields an unlock key (its Argon2id output), which- * opening the chain turns into the Account Key before anything stores it. A key stored before the account had a- * chain is an unlock key; it still opens the chain and is replaced by the Account Key on the next open. The- * Account Key opens the vault key and account private key, which are derived on demand and never stored.- */-/*** The session keys the account key chain gives.** @property vaultEncryptionKey The key that encrypts and decrypts the vault* @property accountPrivateKey The account private key (JWK), null when the account has no keypair- * @property accountKey The key to store for later unlocks, in place of the key the chain was opened with+ * @property accountKey The Account Key to keep, in place of the key the chain was opened with*/class SessionKeys(val vaultEncryptionKey: ByteArray, val accountPrivateKey: String?, val accountKey: ByteArray)/**- * Open the cached account key chain with the stored key: the Account Key, or an unlock key that `accountKey` then- * replaces (Rust `openAccountKeyChain`). Without a chain (account not yet upgraded) the unlock key is the vault key.+ * Open the cached account key chain with the Account Key or the unlock key (Rust `openAccountKeyChain`).*/- fun openAccountKeyChain(storedKey: ByteArray): SessionKeys {- val chainJson = getAccountKeyChain() ?: return SessionKeys(storedKey, null, storedKey)+ 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(storedKey, null, storedKey)+ val encryptedAccountKey = chain.optString("encryptedAccountKey").takeIf { it.isNotEmpty() } ?: return SessionKeys(key, null, key)val 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() }val keys = try {- rustOpenAccountKeyChain(storedKey, encryptedAccountKey, encryptedVek, encryptedPrivateKey)+ rustOpenAccountKeyChain(key, encryptedAccountKey, encryptedVek, encryptedPrivateKey)} catch (e: KeyChainException.UnlockKeyRejected) {throw AppError.UnlockKeyRejected(cause = e)} catch (e: KeyChainException.KeyChainUnreadable) {@@ -262,8 +250,8 @@ class VaultCrypto(/*** Open a session with a key that opens the cached account key chain; the session keeps the Account Key it yields.*/- fun openSession(unlockKey: ByteArray) {- this.unlockKey = openAccountKeyChain(unlockKey).accountKey+ fun openSession(key: ByteArray) {+ accountKey = openAccountKeyChain(key).accountKey}/**@@ -281,10 +269,10 @@ class VaultCrypto(}/**- * Get the unlock key, the keystore and PIN protect.+ * Get the Account Key, the key the keystore and PIN protect.*/- fun getUnlockKey(callback: CryptoOperationCallback, authMethods: String) {- withSession(callback, authMethods) { unlockKey }+ fun getAccountKey(callback: CryptoOperationCallback, authMethods: String) {+ withSession(callback, authMethods) { accountKey }}/**@@ -304,13 +292,13 @@ class VaultCrypto(try {val keystoreKey = Base64.decode(result, Base64.NO_WRAP)openSession(keystoreKey)- unlockKey?.let { LegacyKeyConversion.convertKeystoreKey(keystoreProvider, keystoreKey, it) }+ accountKey?.let { LegacyKeyConversion.convertKeystoreKey(keystoreProvider, keystoreKey, it) }callback.onSuccess(Base64.encodeToString(key(), Base64.NO_WRAP))} catch (e: AppError) {- Log.e(TAG, "The unlock key from the keystore does not open the account key chain", e)+ Log.e(TAG, "The Account Key from the keystore does not open the account key chain", e)callback.onError(e)} catch (e: Exception) {- Log.e(TAG, "The unlock key from the keystore does not open the account key chain", e)+ Log.e(TAG, "The Account Key from the keystore does not open the account key chain", e)callback.onError(AppError.UnlockKeyRejected(cause = e))}}@@ -331,7 +319,7 @@ class VaultCrypto(* Clear the encryption key from memory.*/fun clearKey() {- unlockKey = null+ accountKey = null}// endregion@@ -432,15 +420,15 @@ class VaultCrypto(// region Mobile Login/**- * Encrypts the unlock key using an RSA public key for mobile login. The receiving+ * Encrypts the Account Key using an RSA public key for mobile login. The receiving* client opens the account key chain with it, exactly as after a password login.*/- fun encryptUnlockKeyForMobileLogin(publicKeyJWK: String, authMethods: String): String {+ fun encryptAccountKeyForMobileLogin(publicKeyJWK: String, authMethods: String): String {var result: String? = nullvar error: Exception? = nullval latch = java.util.concurrent.CountDownLatch(1)- getUnlockKey(+ getAccountKey(object : CryptoOperationCallback {override fun onSuccess(key: String) {try {diff --git a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultDatabase.kt b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultDatabase.ktindex a9bffcbce..3c282cd53 100644--- a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultDatabase.kt+++ b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultDatabase.kt@@ -69,7 +69,7 @@ class VaultDatabase(* Check if the vault is unlocked.*/fun isVaultUnlocked(): Boolean {- return crypto.unlockKey != null+ return crypto.accountKey != null}/**diff --git a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultPin.kt b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultPin.ktindex 8844db72d..2d6079fda 100644--- a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultPin.kt+++ b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultPin.kt@@ -39,7 +39,7 @@ sealed class PinUnlockException(message: String) : Exception(message) {/*** Handles PIN unlock functionality for the vault store.- * This component manages PIN-based unlocking by encrypting the unlock key+ * This component manages PIN-based unlocking by encrypting the Account Key* with a key derived from the user's PIN using Argon2id.** Security features:@@ -130,17 +130,16 @@ class VaultPin(/*** Setup PIN unlock.- * Encrypts the unlock key with the PIN and stores it securely.+ * Encrypts the Account Key with the PIN and stores it securely.** @param pin The PIN to set (4+ digits)- * @param unlockKeyBase64 The base64-encoded unlock key to protect+ * @param accountKeyBase64 The base64-encoded Account Key to protect* @throws IllegalArgumentException if PIN format is invalid* @throws Exception if encryption or storage fails*/@Throws(Exception::class)- fun setupPin(pin: String, unlockKeyBase64: String) {- // Decode the unlock key- val unlockKey = Base64.decode(unlockKeyBase64, Base64.NO_WRAP)+ fun setupPin(pin: String, accountKeyBase64: String) {+ val accountKey = Base64.decode(accountKeyBase64, Base64.NO_WRAP)// Generate random saltval salt = ByteArray(16)@@ -149,7 +148,7 @@ class VaultPin(// Derive key from PIN + salt using Argon2idval pinKey = derivePinKey(pin, salt)- // Encrypt the unlock key using AES-GCM+ // Encrypt the Account Key using AES-GCMval cipher = Cipher.getInstance("AES/GCM/NoPadding")val secretKey = SecretKeySpec(pinKey, "AES")@@ -158,7 +157,7 @@ class VaultPin(SecureRandom().nextBytes(iv)cipher.init(Cipher.ENCRYPT_MODE, secretKey, GCMParameterSpec(GCM_TAG_LENGTH, iv))- val encryptedKey = cipher.doFinal(unlockKey)+ val encryptedKey = cipher.doFinal(accountKey)// Combine IV + encrypted dataval combined = ByteArray(iv.size + encryptedKey.size)@@ -185,10 +184,10 @@ class VaultPin(/*** Unlock with PIN.- * Returns the decrypted unlock key.+ * Returns the decrypted Account Key.** @param pin The PIN to use for unlocking- * @return The decrypted unlock key (base64)+ * @return The decrypted key (base64)* @throws PinUnlockException with specific error type and metadata*/@Throws(PinUnlockException::class)@@ -205,7 +204,7 @@ class VaultPin(// Derive key from PIN + saltval pinKey = derivePinKey(pin, salt)- // Decrypt the unlock key+ // Decrypt the PIN-protected keyval cipher = Cipher.getInstance("AES/GCM/NoPadding")val secretKey = SecretKeySpec(pinKey, "AES")cipher.init(Cipher.DECRYPT_MODE, secretKey, GCMParameterSpec(GCM_TAG_LENGTH, iv))@@ -214,7 +213,7 @@ class VaultPin(// Reset failed attempts on successstorePinFailedAttemptsInKeystore(0)- // Return the decrypted unlock key as base64+ // Return the decrypted key as base64return Base64.encodeToString(decryptedKey, Base64.NO_WRAP)} catch (e: Exception) {// Increment failed attemptsdiff --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 69d75e0c9..2134731d5 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@@ -167,18 +167,18 @@ class VaultStore(// region Crypto Methods/**- * Open a session with the unlock key and persist that key to keystore if biometrics+ * Open a session with the unlock key or the Account Key and persist the Account Key to keystore if biometrics* are enabled.*/- fun storeUnlockKey(base64UnlockKey: String) {- crypto.storeUnlockKey(base64UnlockKey, auth.getAuthMethods())+ fun storeAccountKey(base64Key: String) {+ crypto.storeAccountKey(base64Key, auth.getAuthMethods())}/**- * Open a session in memory only with the unlock key.+ * Open a session in memory only with the unlock key or the Account Key.*/- fun storeUnlockKeyInMemory(base64UnlockKey: String) {- crypto.storeUnlockKeyInMemory(base64UnlockKey)+ fun storeAccountKeyInMemory(base64Key: String) {+ crypto.storeAccountKeyInMemory(base64Key)}/**@@ -198,10 +198,10 @@ class VaultStore(}/**- * Get the unlock key, the keystore and PIN protect.+ * Get the Account Key, the key the keystore and PIN protect.*/- fun getUnlockKey(callback: CryptoOperationCallback) {- crypto.getUnlockKey(callback, auth.getAuthMethods())+ fun getAccountKey(callback: CryptoOperationCallback) {+ crypto.getAccountKey(callback, auth.getAuthMethods())}/**@@ -240,7 +240,7 @@ class VaultStore(}/**- * The account private key (JWK) of the unlocked session, derived from the unlock key; null for an account without a keypair.+ * The account private key (JWK) of the unlocked session, derived from the Account Key; null for an account without a keypair.*/internal val accountPrivateKey: String?get() = crypto.accountPrivateKey@@ -272,10 +272,10 @@ class VaultStore(}/**- * Encrypts the unlock key using an RSA public key for mobile login.+ * Encrypts the Account Key using an RSA public key for mobile login.*/- fun encryptUnlockKeyForMobileLogin(publicKeyJWK: String): String {- return crypto.encryptUnlockKeyForMobileLogin(publicKeyJWK, auth.getAuthMethods())+ fun encryptAccountKeyForMobileLogin(publicKeyJWK: String): String {+ return crypto.encryptAccountKeyForMobileLogin(publicKeyJWK, auth.getAuthMethods())}/**@@ -344,10 +344,10 @@ class VaultStore(* Unlock the vault.*/fun unlockVault() {- // A nil-to-non-nil transition means the keystore just released the unlock key after biometric.- val hadKeyInMemory = crypto.unlockKey != null+ // A nil-to-non-nil transition means the keystore just released the Account Key after biometric.+ val hadKeyInMemory = crypto.accountKey != nulldatabase.unlockVault(auth.getAuthMethods())- if (!hadKeyInMemory && crypto.unlockKey != null) {+ if (!hadKeyInMemory && crypto.accountKey != null) {markSuccessfulAuth()}}@@ -476,11 +476,11 @@ class VaultStore(}/**- * Attempts to get all items using only the unlock key held in memory.+ * Attempts to get all items using only the Account Key held in memory.*/fun tryGetAllItems(callback: ItemOperationCallback): Boolean {- if (crypto.unlockKey == null) {- android.util.Log.d(TAG, "Unlock key not in memory, authentication required")+ if (crypto.accountKey == null) {+ android.util.Log.d(TAG, "Account Key not in memory, authentication required")return false}@@ -514,8 +514,8 @@ class VaultStore(if (!wasBiometricEnabled && isBiometricEnabled) {try {- crypto.storeUnlockKey(- android.util.Base64.encodeToString(crypto.unlockKey, android.util.Base64.NO_WRAP),+ crypto.storeAccountKey(+ android.util.Base64.encodeToString(crypto.accountKey, android.util.Base64.NO_WRAP),authMethods,)} catch (e: Exception) {@@ -937,12 +937,12 @@ class VaultStore(* Setup PIN unlock.*/@Throws(Exception::class)- fun setupPin(pinValue: String, unlockKeyBase64: String) {- pin.setupPin(pinValue, unlockKeyBase64)+ fun setupPin(pinValue: String, accountKeyBase64: String) {+ pin.setupPin(pinValue, accountKeyBase64)}/**- * Unlock with PIN. Returns the key the PIN protects, to open the session with.+ * Unlock with PIN. Returns the Account Key, to open the session with.*/@Throws(Exception::class)fun unlockWithPin(pinValue: String): String {diff --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 cc2c9e9bc..b8fa6cd53 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@@ -95,15 +95,15 @@ class VaultSync(/*** Resolve the vault key right after login: the account's key chain is opened with the unlock key- * and cached as-is. The session then opens from that chain like every later unlock, and the keystore keeps the- * unlock key. Returns the vault key (base64).+ * and cached as-is. The session then opens from that chain like every later unlock, and the session keeps the+ * Account Key. Returns the vault key (base64).*/suspend fun resolveVaultKey(webApiService: WebApiService, derivedKeyBase64: String): String {val result = run("resolveVaultKey", webApiService, encryptionKey = derivedKeyBase64)if (!result.optBoolean("success", false)) {throw syncError(result)}- vaultStore.storeUnlockKey(derivedKeyBase64)+ vaultStore.storeAccountKey(derivedKeyBase64)return vaultStore.getEncryptionKeyBase64() ?: derivedKeyBase64}diff --git a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/keystoreprovider/AndroidKeystoreProvider.kt b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/keystoreprovider/AndroidKeystoreProvider.ktindex b7fcc5f50..ecfb5ef6b 100644--- a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/keystoreprovider/AndroidKeystoreProvider.kt+++ b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/keystoreprovider/AndroidKeystoreProvider.kt@@ -55,7 +55,7 @@ class AndroidKeystoreProvider(private const val KEYSTORE_ALIAS = "alias_vault_key"/**- * The filename for the encrypted unlock key.+ * The filename for the encrypted Account Key.*/private const val ENCRYPTED_KEY_FILE = "encrypted_vault_key"diff --git a/apps/mobile-app/android/app/src/test/java/net/aliasvault/app/nativevaultmanager/VaultStoreTest.kt b/apps/mobile-app/android/app/src/test/java/net/aliasvault/app/nativevaultmanager/VaultStoreTest.ktindex a4ffd4cd9..f78e63385 100644--- a/apps/mobile-app/android/app/src/test/java/net/aliasvault/app/nativevaultmanager/VaultStoreTest.kt+++ b/apps/mobile-app/android/app/src/test/java/net/aliasvault/app/nativevaultmanager/VaultStoreTest.kt@@ -19,7 +19,7 @@ import kotlin.test.assertTrue@Config(sdk = [28], manifest = Config.NONE)class VaultStoreTest {private lateinit var vaultStore: VaultStore- private val testUnlockKeyBase64 = "/9So3C83JLDIfjsF0VQOc4rz1uAFtIseW7yrUuztAD0=" // 32 bytes for AES-256+ private val testAccountKeyBase64 = "/9So3C83JLDIfjsF0VQOc4rz1uAFtIseW7yrUuztAD0=" // 32 bytes for AES-256@Beforefun setup() {@@ -29,7 +29,7 @@ class VaultStoreTest {// Initialize the VaultStore instance with a mock file provider that// is only used for testing purposesvaultStore = VaultStore(TestStorageProvider(), TestKeystoreProvider())- vaultStore.storeUnlockKey(testUnlockKeyBase64)+ vaultStore.storeAccountKey(testAccountKeyBase64)vaultStore.storeEncryptedDatabase(encryptedDb)val metadata = """@@ -121,7 +121,7 @@ class VaultStoreTest {// Then, try to re-load the database and ensure the __EFMigrationsHistory table still exists.// This asserts that the database commit results in a properly exported and encrypted database file.vaultStore.clearCache()- vaultStore.storeUnlockKey(testUnlockKeyBase64)+ vaultStore.storeAccountKey(testAccountKeyBase64)vaultStore.unlockVault()// Do a querydiff --git a/apps/mobile-app/app/(tabs)/settings/mobile-unlock/confirm.tsx b/apps/mobile-app/app/(tabs)/settings/mobile-unlock/confirm.tsxindex e28a7f2d7..29b9187ed 100644--- a/apps/mobile-app/app/(tabs)/settings/mobile-unlock/confirm.tsx+++ b/apps/mobile-app/app/(tabs)/settings/mobile-unlock/confirm.tsx@@ -152,7 +152,7 @@ export default function MobileUnlockConfirmScreen() : React.ReactNode {};/**- * Handle approve: check the selected number, re-authenticate the user, then hand over the unlock key.+ * Handle approve: check the selected number, re-authenticate the user, then hand over the Account Key.*/const handleApprove = async () : Promise<void> => {if (!scan || !request || !selectedCode || approveDelay > 0) {@@ -182,8 +182,9 @@ export default function MobileUnlockConfirmScreen() : React.ReactNode {}// Encrypt with the public key that was verified against the QR code.- const encryptedUnlockKey = await NativeVaultManager.encryptUnlockKeyForMobileLogin(request.details.clientPublicKey);- await webApi.post<MobileLoginSubmitRequest, void>('auth/mobile-login/submit', { requestId: scan.requestId, encryptedUnlockKey }, false);+ const encryptedAccountKey = await NativeVaultManager.encryptAccountKeyForMobileLogin(request.details.clientPublicKey);+ const submitRequest: MobileLoginSubmitRequest = { requestId: scan.requestId, encryptedUnlockKey: encryptedAccountKey };+ await webApi.post<MobileLoginSubmitRequest, void>('auth/mobile-login/submit', submitRequest, false);showResult(true);} catch (error) {diff --git a/apps/mobile-app/app/(tabs)/settings/vault-unlock.tsx b/apps/mobile-app/app/(tabs)/settings/vault-unlock.tsxindex 9e2bd8027..40cb1f850 100644--- a/apps/mobile-app/app/(tabs)/settings/vault-unlock.tsx+++ b/apps/mobile-app/app/(tabs)/settings/vault-unlock.tsx@@ -43,7 +43,7 @@ export default function VaultUnlockSettingsScreen() : React.ReactNode {const methods = await AppUnlockUtility.getEnabledAuthMethods();- // Check if biometric unlock is actually functional (validates stored key)+ // Check if biometric unlock is actually functional (validates the Account Key in the keychain)if (methods.includes('faceid') && deviceAvailable) {const unlockAvailable = await AppUnlockUtility.isBiometricUnlockAvailable();diff --git a/apps/mobile-app/app/login.tsx b/apps/mobile-app/app/login.tsxindex 587fce293..c0a2ffd10 100644--- a/apps/mobile-app/app/login.tsx+++ b/apps/mobile-app/app/login.tsx@@ -1,7 +1,7 @@import { Buffer } from 'buffer';import { describeAuthError, formatErrorMessage } from '@aliasvault/client/auth/AuthErrorMessage';-import { SrpAuthService, type LoginCredentials } from '@aliasvault/client/auth/SrpAuthService';+import { SrpAuthService, type PreparedCredentials } from '@aliasvault/client/auth/SrpAuthService';import { SrpLoginService } from '@aliasvault/client/auth/SrpLoginService';import { MaterialIcons } from '@expo/vector-icons';import { LinearGradient } from 'expo-linear-gradient';@@ -63,8 +63,7 @@ export default function LoginScreen() : React.ReactNode {const [twoFactorRequired, setTwoFactorRequired] = useState(false);const [twoFactorCode, setTwoFactorCode] = useState('');const [initiateLoginResponse, setInitiateLoginResponse] = useState<LoginResponse | null>(null);- const [loginCredentials, setLoginCredentials] = useState<LoginCredentials | null>(null);- const [passwordHashBase64, setPasswordHashBase64] = useState<string | null>(null);+ const [loginCredentials, setLoginCredentials] = useState<PreparedCredentials | null>(null);const [loginStatus, setLoginStatus] = useState<string | null>(null);const [showPassword, setShowPassword] = useState(false);@@ -174,13 +173,13 @@ export default function LoginScreen() : React.ReactNode {* Process the vault response by storing the vault and logging in the user.* @param token - The token to use for the vault* @param refreshToken - The refresh token to use for the vault- * @param passwordHashBase64 - The password hash base64+ * @param unlockKeyBase64 - The unlock key (base64), the Argon2id output of the password* @param initiateLoginResponse - The initiate login response*/const processVaultResponse = async (token: string,refreshToken: string,- passwordHashBase64: string,+ unlockKeyBase64: string,initiateLoginResponse: LoginResponse) : Promise<void> => {// Get biometric display name@@ -209,7 +208,7 @@ export default function LoginScreen() : React.ReactNode {await continueProcessVaultResponse(token,refreshToken,- passwordHashBase64,+ unlockKeyBase64,initiateLoginResponse);}@@ -225,7 +224,7 @@ export default function LoginScreen() : React.ReactNode {await continueProcessVaultResponse(token,refreshToken,- passwordHashBase64,+ unlockKeyBase64,initiateLoginResponse);}@@ -241,7 +240,7 @@ export default function LoginScreen() : React.ReactNode {await continueProcessVaultResponse(token,refreshToken,- passwordHashBase64,+ unlockKeyBase64,initiateLoginResponse);}@@ -251,14 +250,13 @@ export default function LoginScreen() : React.ReactNode {* Continue processing the vault response after biometric choice* @param token - The token to use for the vault* @param refreshToken - The refresh token to use for the vault- * @param passwordHashBase64 - The password hash base64+ * @param unlockKeyBase64 - The unlock key (base64), the Argon2id output of the password* @param initiateLoginResponse - The initiate login response- * @param unlockKeyDerivationParams - The encryption key derivation parameters*/const continueProcessVaultResponse = async (token: string,refreshToken: string,- passwordHashBase64: string,+ unlockKeyBase64: string,initiateLoginResponse: LoginResponse) : Promise<void> => {const unlockKeyDerivationParams : UnlockKeyDerivationParams = {@@ -275,11 +273,10 @@ export default function LoginScreen() : React.ReactNode {await dbContext.storeUnlockKeyDerivationParams(unlockKeyDerivationParams);/*- * The derived key is the unlock key. The Rust core opens the account's key chain with the KEK derived from it- * (fetched from the server, or the cached one when offline) and caches the chain as-is. The session, biometrics- * and PIN keep the Account Key and open the chain from it on every unlock.+ * The Rust core opens the account's key chain (fetched from the server, or the cached one when offline) with the+ * KEK derived from the unlock key and caches the chain as-is. The session keeps the Account Key it yields.*/- await NativeVaultManager.resolveVaultKey(passwordHashBase64);+ await NativeVaultManager.resolveVaultKey(unlockKeyBase64);/** Forced logout recovery check:@@ -374,7 +371,6 @@ export default function LoginScreen() : React.ReactNode {setTwoFactorRequired(false);setTwoFactorCode('');setLoginCredentials(null);- setPasswordHashBase64(null);setInitiateLoginResponse(null);setLoginStatus(null);router.replace('/(tabs)/items');@@ -401,15 +397,15 @@ export default function LoginScreen() : React.ReactNode {try {const initiateLoginResponse = await srpUtil.initiateLogin(SrpAuthService.normalizeUsername(credentials.username));- const passwordHash = await EncryptionUtility.deriveKeyFromPassword(+ const unlockKey = await EncryptionUtility.deriveKeyFromPassword(credentials.password,initiateLoginResponse.salt,initiateLoginResponse.encryptionType,initiateLoginResponse.encryptionSettings);- const passwordHashBase64 = Buffer.from(passwordHash).toString('base64');- const passwordCredentials = await SrpAuthService.loginCredentials(passwordHashBase64, initiateLoginResponse, credentials.username);+ const unlockKeyBase64 = Buffer.from(unlockKey).toString('base64');+ const passwordCredentials = await SrpAuthService.loginCredentials(unlockKeyBase64, initiateLoginResponse, credentials.username);setLoginStatus(t('auth.validatingCredentials'));await new Promise(resolve => requestAnimationFrame(resolve));@@ -423,7 +419,6 @@ export default function LoginScreen() : React.ReactNode {if (validationResponse.requiresTwoFactor) {setInitiateLoginResponse(initiateLoginResponse);setLoginCredentials(passwordCredentials);- setPasswordHashBase64(passwordHashBase64);setTwoFactorRequired(true);setIsLoading(false);setLoginStatus(null);@@ -440,7 +435,7 @@ export default function LoginScreen() : React.ReactNode {await processVaultResponse(validationResponse.token.token,validationResponse.token.refreshToken,- passwordHashBase64,+ passwordCredentials.unlockKeyBase64,initiateLoginResponse);} catch (err) {@@ -461,7 +456,7 @@ export default function LoginScreen() : React.ReactNode {await new Promise(resolve => requestAnimationFrame(resolve));try {- if (!loginCredentials || !passwordHashBase64 || !initiateLoginResponse) {+ if (!loginCredentials || !initiateLoginResponse) {throw new Error('Required login data not found');}@@ -488,7 +483,7 @@ export default function LoginScreen() : React.ReactNode {await processVaultResponse(validationResponse.token.token,validationResponse.token.refreshToken,- passwordHashBase64,+ loginCredentials.unlockKeyBase64,initiateLoginResponse);} catch (err) {@@ -736,7 +731,6 @@ export default function LoginScreen() : React.ReactNode {setTwoFactorRequired(false);setTwoFactorCode('');setLoginCredentials(null);- setPasswordHashBase64(null);setInitiateLoginResponse(null);setError(null);}}diff --git a/apps/mobile-app/context/AuthContext.tsx b/apps/mobile-app/context/AuthContext.tsxindex 12f04c991..7b2ab23c0 100644--- a/apps/mobile-app/context/AuthContext.tsx+++ b/apps/mobile-app/context/AuthContext.tsx@@ -252,7 +252,7 @@ export const AuthProvider: React.FC<{}, []);/**- * Verify the password. Returns the current password hash if the password is correct, otherwise returns null.+ * Verify the password. Returns its unlock key (base64) if the password is correct, otherwise returns null.*/const verifyPassword = useCallback(async (password: string): Promise<string | null> => {// Get the key derivation parameters@@ -261,23 +261,23 @@ export const AuthProvider: React.FC<{throw new Error('Failed to verify current password. Please try again.');}- // Derive the encryption key from the password using the stored parameters- const passwordHash = await EncryptionUtility.deriveKeyFromPassword(+ // Derive the unlock key from the password using the stored parameters+ const unlockKey = await EncryptionUtility.deriveKeyFromPassword(password,params.salt,params.encryptionType,params.encryptionSettings);- const currentPasswordHashBase64 = Buffer.from(passwordHash).toString('base64');+ const unlockKeyBase64 = Buffer.from(unlockKey).toString('base64');// Check if the current password is correct- const isValid = await dbContext.verifyUnlockKey(currentPasswordHashBase64);+ const isValid = await dbContext.verifyUnlockKey(unlockKeyBase64);if (!isValid) {return null;}- return currentPasswordHashBase64;+ return unlockKeyBase64;}, [dbContext, getUnlockKeyDerivationParams]);/**diff --git a/apps/mobile-app/context/DbContext.tsx b/apps/mobile-app/context/DbContext.tsxindex ae40d6160..11e87f51a 100644--- a/apps/mobile-app/context/DbContext.tsx+++ b/apps/mobile-app/context/DbContext.tsx@@ -32,7 +32,7 @@ type DbContextType = {*/shouldSuppressEmailErrors: () => boolean;refreshSyncState: () => Promise<void>;- storeUnlockKey: (derivedKey: string) => Promise<void>;+ storeAccountKey: (derivedKey: string) => Promise<void>;storeUnlockKeyDerivationParams: (keyDerivationParams: UnlockKeyDerivationParams) => Promise<void>;requiresLegacySqliteBlobMigration: () => Promise<boolean>;hasPendingMigrations: () => Promise<boolean>;@@ -112,15 +112,13 @@ export const DbProvider: React.FC<{ children: React.ReactNode }> = ({ children }}, []);/**- * 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.+ * 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.** @param derivedKey The password-derived unlock key*/- const storeUnlockKey = useCallback(async (derivedKey: string) => {- await sqliteClient.storeUnlockKey(derivedKey- );+ const storeAccountKey = useCallback(async (derivedKey: string) => {+ await sqliteClient.storeAccountKey(derivedKey);}, [sqliteClient]);/**@@ -271,7 +269,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.storeUnlockKeyInMemory(derivedKey);+ await sqliteClient.storeAccountKeyInMemory(derivedKey);await unlockVault();@@ -285,7 +283,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.storeUnlockKey(derivedKey);+ await sqliteClient.storeAccountKey(derivedKey);}return true;}@@ -300,7 +298,7 @@ export const DbProvider: React.FC<{ children: React.ReactNode }> = ({ children }*/const verifyUnlockKey = useCallback(async (derivedKey: string): Promise<boolean> => {try {- await sqliteClient.storeUnlockKeyInMemory(derivedKey);+ await sqliteClient.storeAccountKeyInMemory(derivedKey);await unlockVault();const version = await sqliteClient.getDatabaseVersion();@@ -334,11 +332,11 @@ export const DbProvider: React.FC<{ children: React.ReactNode }> = ({ children }testDatabaseConnection,verifyUnlockKey,unlockVault,- storeUnlockKey,+ storeAccountKey,storeUnlockKeyDerivationParams,checkStoredVault,setDatabaseAvailable,- }), [sqliteClient, dbInitialized, dbAvailable, isDirty, dirtyScopes, isSyncing, isUploading, isOffline, setIsSyncing, setIsUploading, setIsOffline, shouldSuppressEmailErrors, refreshSyncState, requiresLegacySqliteBlobMigration, hasPendingMigrations, clearDatabase, getVaultMetadata, testDatabaseConnection, verifyUnlockKey, unlockVault, storeUnlockKey, 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]);return (<DbContext.Provider value={contextValue}>diff --git a/apps/mobile-app/ios/Autofill/CredentialProviderViewController.swift b/apps/mobile-app/ios/Autofill/CredentialProviderViewController.swiftindex d6e717f99..7ee1eda5f 100644--- a/apps/mobile-app/ios/Autofill/CredentialProviderViewController.swift+++ b/apps/mobile-app/ios/Autofill/CredentialProviderViewController.swift@@ -239,10 +239,10 @@ public class CredentialProviderViewController: ASCredentialProviderViewControlleguard let self = self else { return }// Attempt to unlock with PIN- let unlockKeyBase64 = try vaultStore.unlockWithPin(pin)+ let accountKeyBase64 = try vaultStore.unlockWithPin(pin)- // Open the session with the unlock key and unlock- try vaultStore.storeUnlockKey(base64Key: unlockKeyBase64)+ // Open the session with the Account Key and unlock+ try vaultStore.storeAccountKey(base64Key: accountKeyBase64)try vaultStore.unlockVault()// Process the credential requestdiff --git a/apps/mobile-app/ios/Autofill/UnlockCoordinator.swift b/apps/mobile-app/ios/Autofill/UnlockCoordinator.swiftindex 7029a83e9..618db65bb 100644--- a/apps/mobile-app/ios/Autofill/UnlockCoordinator.swift+++ b/apps/mobile-app/ios/Autofill/UnlockCoordinator.swift@@ -83,10 +83,10 @@ class UnlockCoordinator: ObservableObject {guard let self = self else { return }// Attempt to unlock with PIN- let unlockKeyBase64 = try self.vaultStore.unlockWithPin(pin)+ let accountKeyBase64 = try self.vaultStore.unlockWithPin(pin)- // Open the session with the unlock key- try self.vaultStore.storeUnlockKey(base64Key: unlockKeyBase64)+ // Open the session with the Account Key+ try self.vaultStore.storeAccountKey(base64Key: accountKeyBase64)// Now unlock the vault with the key in memorytry self.vaultStore.unlockVault()diff --git a/apps/mobile-app/ios/NativeVaultManager/RCTNativeVaultManager.mm b/apps/mobile-app/ios/NativeVaultManager/RCTNativeVaultManager.mmindex 2d0b07227..8e13e3d30 100644--- a/apps/mobile-app/ios/NativeVaultManager/RCTNativeVaultManager.mm+++ b/apps/mobile-app/ios/NativeVaultManager/RCTNativeVaultManager.mm@@ -97,12 +97,12 @@[vaultManager storeMetadata:metadata resolver:resolve rejecter:reject];}-- (void)storeUnlockKeyInMemory:(NSString *)base64UnlockKey resolve:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject {- [vaultManager storeUnlockKeyInMemory:base64UnlockKey resolver:resolve rejecter:reject];+- (void)storeAccountKeyInMemory:(NSString *)base64Key resolve:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject {+ [vaultManager storeAccountKeyInMemory:base64Key resolver:resolve rejecter:reject];}-- (void)storeUnlockKey:(NSString *)base64UnlockKey resolve:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject {- [vaultManager storeUnlockKey:base64UnlockKey resolver:resolve rejecter:reject];+- (void)storeAccountKey:(NSString *)base64Key resolve:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject {+ [vaultManager storeAccountKey:base64Key resolver:resolve rejecter:reject];}- (void)clearEncryptionKeyFromMemory:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject {@@ -355,8 +355,8 @@// MARK: - Mobile Login-- (void)encryptUnlockKeyForMobileLogin:(NSString *)publicKeyJWK resolve:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject {- [vaultManager encryptUnlockKeyForMobileLogin:publicKeyJWK resolver:resolve rejecter:reject];+- (void)encryptAccountKeyForMobileLogin:(NSString *)publicKeyJWK resolve:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject {+ [vaultManager encryptAccountKeyForMobileLogin:publicKeyJWK resolver:resolve rejecter:reject];}// MARK: - Re-authenticationdiff --git a/apps/mobile-app/ios/NativeVaultManager/VaultManager.swift b/apps/mobile-app/ios/NativeVaultManager/VaultManager.swiftindex 136456883..19f9ca796 100644--- a/apps/mobile-app/ios/NativeVaultManager/VaultManager.swift+++ b/apps/mobile-app/ios/NativeVaultManager/VaultManager.swift@@ -62,30 +62,30 @@ public class VaultManager: NSObject {}}- /// Open a session in memory with the unlock key or stored key, without keychain persistence.+ /// 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.@objc- func storeUnlockKeyInMemory(_ base64UnlockKey: String,- resolver resolve: @escaping RCTPromiseResolveBlock,- rejecter reject: @escaping RCTPromiseRejectBlock) {+ func storeAccountKeyInMemory(_ base64Key: String,+ resolver resolve: @escaping RCTPromiseResolveBlock,+ rejecter reject: @escaping RCTPromiseRejectBlock) {do {- try vaultStore.storeUnlockKeyInMemory(base64Key: base64UnlockKey)+ try vaultStore.storeAccountKeyInMemory(base64Key: base64Key)resolve(nil)} catch {- reject("ERR_STORE_KEY_MEMORY", "Failed to store unlock key in memory: \(error.localizedDescription)", error)+ reject("ERR_STORE_KEY_MEMORY", "Failed to store Account Key in memory: \(error.localizedDescription)", error)}}- /// Open a session with the unlock key or stored key AND persist the stored key to keychain if Face ID is enabled.+ /// 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 storeUnlockKey(_ base64UnlockKey: String,- resolver resolve: @escaping RCTPromiseResolveBlock,- rejecter reject: @escaping RCTPromiseRejectBlock) {+ func storeAccountKey(_ base64Key: String,+ resolver resolve: @escaping RCTPromiseResolveBlock,+ rejecter reject: @escaping RCTPromiseRejectBlock) {do {- try vaultStore.storeUnlockKey(base64Key: base64UnlockKey)+ try vaultStore.storeAccountKey(base64Key: base64Key)resolve(nil)} catch {- reject("KEYCHAIN_ERROR", "Failed to store unlock key: \(error.localizedDescription)", error)+ reject("KEYCHAIN_ERROR", "Failed to store Account Key: \(error.localizedDescription)", error)}}@@ -970,10 +970,10 @@ public class VaultManager: NSObject {}// Unlock vault with PIN- let unlockKeyBase64 = try self.vaultStore.unlockWithPin(pin)+ let accountKeyBase64 = try self.vaultStore.unlockWithPin(pin)- // Open the session with the unlock key- try self.vaultStore.storeUnlockKey(base64Key: unlockKeyBase64)+ // Open the session with the Account Key+ try self.vaultStore.storeAccountKey(base64Key: accountKeyBase64)// Now unlock the vault with the key in memorytry self.vaultStore.unlockVault()@@ -1041,7 +1041,7 @@ public class VaultManager: NSObject {}// Open the session in memory only- try self.vaultStore.storeUnlockKeyInMemory(base64Key: unlockKeyBase64)+ try self.vaultStore.storeAccountKeyInMemory(base64Key: unlockKeyBase64)// Unlock the vaulttry self.vaultStore.unlockVault()@@ -1132,12 +1132,12 @@ public class VaultManager: NSObject {}@objc- func encryptUnlockKeyForMobileLogin(_ publicKeyJWK: String,- resolver resolve: @escaping RCTPromiseResolveBlock,- rejecter reject: @escaping RCTPromiseRejectBlock) {+ func encryptAccountKeyForMobileLogin(_ publicKeyJWK: String,+ resolver resolve: @escaping RCTPromiseResolveBlock,+ rejecter reject: @escaping RCTPromiseRejectBlock) {do {- // Get the encryption key and encrypt it with the provided public key- let encryptedData = try vaultStore.encryptUnlockKeyForMobileLogin(publicKeyJWK: publicKeyJWK)+ // Encrypt the Account Key with the provided public key+ let encryptedData = try vaultStore.encryptAccountKeyForMobileLogin(publicKeyJWK: publicKeyJWK)// Return the encrypted data as base64 stringlet base64Encrypted = encryptedData.base64EncodedString()@@ -1391,7 +1391,7 @@ public class VaultManager: NSObject {throw NSError(domain: "VaultManager", code: -1, userInfo: [NSLocalizedDescriptionKey: "Incorrect password"])}- try self.vaultStore.storeUnlockKeyInMemory(base64Key: unlockKeyBase64)+ try self.vaultStore.storeAccountKeyInMemory(base64Key: unlockKeyBase64)// Success - dismiss and resolveawait MainActor.run {@@ -1576,8 +1576,8 @@ private enum RustCoreDispatcher {case "deriveKek": return try json(bytes: RustCoreFramework.deriveKek(unlockKey: try args.data(0)))case "deriveSrpPasswordHash": return try json(try RustCoreFramework.deriveSrpPasswordHash(unlockKey: try args.data(0), encryptionType: try args.string(1)))case "openAccountKeyChain":- let storedKey = try args.data(0)- return try openKeyChain(storedKey: storedKey, encryptedAccountKey: try args.string(1), encryptedVek: try args.string(2), encryptedAccountPrivateKey: args.optionalString(3))+ 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 "srpGenerateSalt": return try json(RustCoreFramework.srpGenerateSalt())case "srpDerivePrivateKey":@@ -1613,12 +1613,11 @@ private enum RustCoreDispatcher {return text}- /// JSON-encode raw bytes as a base64 string./// Open a key chain and report the outcome as the `KeyChainOpenResult` JSON the client core expects.- private static func openKeyChain(storedKey: Data, encryptedAccountKey: String, encryptedVek: String, encryptedAccountPrivateKey: String?) throws -> String {+ private static func openKeyChain(key: Data, encryptedAccountKey: String, encryptedVek: String, encryptedAccountPrivateKey: String?) throws -> String {do {let keys = try RustCoreFramework.openAccountKeyChain(- storedKey: storedKey, encryptedAccountKey: encryptedAccountKey, encryptedVek: encryptedVek, encryptedAccountPrivateKey: encryptedAccountPrivateKey+ storedKey: key, encryptedAccountKey: encryptedAccountKey, encryptedVek: encryptedVek, encryptedAccountPrivateKey: encryptedAccountPrivateKey)return try json(["status": "opened",@@ -1633,6 +1632,7 @@ private enum RustCoreDispatcher {}}+ /// JSON-encode raw bytes as a base64 string.private static func json(bytes: Data) throws -> String {return try json(bytes.base64EncodedString())}diff --git a/apps/mobile-app/ios/VaultStoreKit/Enums/AppError.swift b/apps/mobile-app/ios/VaultStoreKit/Enums/AppError.swiftindex bed827b5f..522f945e4 100644--- a/apps/mobile-app/ios/VaultStoreKit/Enums/AppError.swift+++ b/apps/mobile-app/ios/VaultStoreKit/Enums/AppError.swift@@ -25,13 +25,13 @@ public enum AppError: Error {case syncVaultFetchFailed(message: String)// Decryption errors- /// The locally stored vault does not decrypt with the session key.+ /// The locally stored vault does not decrypt with the Account Key.case vaultDecryptFailed/// The unlock key does not open the account key (wrong password or PIN).case unlockKeyRejected/// The account key opened, the vault encryption key under it did not.case keyChainUnreadable(message: String)- /// The session key does not open the key chain the server holds; only a re-login recovers.+ /// The Account Key does not open the key chain the server holds; only a re-login recovers.case keyOutOfSync/// A server manifest or bucket fails its hash check or does not decrypt.case serverVaultDecryptFailed(message: String)diff --git a/apps/mobile-app/ios/VaultStoreKit/Services/VaultSync.swift b/apps/mobile-app/ios/VaultStoreKit/Services/VaultSync.swiftindex d29cc5218..487711261 100644--- a/apps/mobile-app/ios/VaultStoreKit/Services/VaultSync.swift+++ b/apps/mobile-app/ios/VaultStoreKit/Services/VaultSync.swift@@ -74,15 +74,14 @@ internal final class VaultSync {}/// Resolve the vault key right after login: the account's key chain is opened with the unlock key (the password's- /// Argon2id output) and cached as-is. The session then opens from that chain like every later unlock, and keeps- /// the Account Key; an account not yet upgraded has no chain and its unlock key is the vault key. Returns the vault- /// key (base64).+ /// Argon2id output) and cached as-is. The session then opens from that chain like every later unlock, and the session+ /// keeps the Account Key. Returns the vault key (base64).func resolveVaultKey(using webApiService: WebApiService, derivedKeyBase64: String) async throws -> String {let result = try await run("resolveVaultKey", using: webApiService, encryptionKey: derivedKeyBase64)guard result["success"] as? Bool == true else {throw Self.syncError(from: result)}- try vaultStore.storeUnlockKey(base64Key: derivedKeyBase64)+ try vaultStore.storeAccountKey(base64Key: derivedKeyBase64)return try vaultStore.getEncryptionKeyBase64()}diff --git a/apps/mobile-app/ios/VaultStoreKit/VaultStore+Auth.swift b/apps/mobile-app/ios/VaultStoreKit/VaultStore+Auth.swiftindex 51a2e980f..36bb3dfe6 100644--- a/apps/mobile-app/ios/VaultStoreKit/VaultStore+Auth.swift+++ b/apps/mobile-app/ios/VaultStoreKit/VaultStore+Auth.swift@@ -22,10 +22,10 @@ extension VaultStore {throw error}} else {- print("Face ID is now enabled, persisting unlock key in memory to keychain")+ print("Face ID is now enabled, persisting Account Key in memory to keychain")do {- guard let keyData = self.unlockKey else {- print("Unlock key is empty, skipping keychain persistence")+ guard let keyData = self.accountKey else {+ print("Account Key is empty, skipping keychain persistence")return}diff --git a/apps/mobile-app/ios/VaultStoreKit/VaultStore+Cache.swift b/apps/mobile-app/ios/VaultStoreKit/VaultStore+Cache.swiftindex 5284c1708..51507de27 100644--- a/apps/mobile-app/ios/VaultStoreKit/VaultStore+Cache.swift+++ b/apps/mobile-app/ios/VaultStoreKit/VaultStore+Cache.swift@@ -4,10 +4,10 @@ import VaultUtils/// Extension for the VaultStore class to handle cache managementextension VaultStore {- /// Clear the memory - remove the unlock key and decrypted database from memory+ /// Clear the memory - remove the Account Key and decrypted database from memorypublic func clearCache() {- print("Clearing cache - removing unlock key and decrypted database from memory")- self.unlockKey = nil+ print("Clearing cache - removing Account Key and decrypted database from memory")+ self.accountKey = nilself.dbConnection = nilclearLastSuccessfulAuth()}@@ -20,7 +20,7 @@ extension VaultStore {print("Clearing session - preserving vault data for recovery")// Clear in-memory data only- self.unlockKey = nil+ self.accountKey = nilself.dbConnection = nilclearLastSuccessfulAuth()@@ -79,7 +79,7 @@ extension VaultStore {print("Cleared UserDefaults")// Clear the cache to remove all in-memory data- self.unlockKey = nil+ self.accountKey = nilself.dbConnection = nilself.enabledAuthMethods = []self.autoLockTimeout = VaultConstants.defaultAutoLockTimeoutdiff --git a/apps/mobile-app/ios/VaultStoreKit/VaultStore+Crypto.swift b/apps/mobile-app/ios/VaultStoreKit/VaultStore+Crypto.swiftindex 677197a7c..d6f388e25 100644--- a/apps/mobile-app/ios/VaultStoreKit/VaultStore+Crypto.swift+++ b/apps/mobile-app/ios/VaultStoreKit/VaultStore+Crypto.swift@@ -24,36 +24,35 @@ extension VaultStore {return derivedKey}- /// Open a session in memory with the unlock key (the password's Argon2id output) or stored key, without keychain persistence.+ /// 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.- public func storeUnlockKeyInMemory(base64Key: String) throws {+ public func storeAccountKeyInMemory(base64Key: String) throws {guard let keyData = Data(base64Encoded: base64Key) else {throw NSError(domain: "VaultStore", code: 6, userInfo: [NSLocalizedDescriptionKey: "Invalid base64 key"])}- try openSession(unlockKey: keyData)+ try openSession(with: keyData)print("Opened session in memory only (no keychain persistence)")}- /// Clear the unlock key from memory.- /// This forces getEncryptionKey() to fetch the unlock key from keychain on next access.+ /// Clear the Account Key from memory.+ /// This forces getEncryptionKey() to fetch the Account Key from keychain on next access.public func clearEncryptionKeyFromMemory() {- self.unlockKey = nil+ self.accountKey = nilclearLastSuccessfulAuth()- print("Cleared unlock key from memory")+ print("Cleared Account Key from memory")}- /// Open a session in memory with the unlock key (the password's Argon2id output) or stored key AND persist the stored key to keychain- /// if Face ID is enabled.- public func storeUnlockKey(base64Key: String) throws {+ /// 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.+ public func storeAccountKey(base64Key: String) throws {// First open the session in memory- try storeUnlockKeyInMemory(base64Key: base64Key)+ try storeAccountKeyInMemory(base64Key: base64Key)// Then persist to keychain if Face ID is enabled AND keystore is available- if self.enabledAuthMethods.contains(.faceID), let keyData = self.unlockKey {+ if self.enabledAuthMethods.contains(.faceID), let keyData = self.accountKey {if isKeystoreAvailable() {try storeKeyInKeychain(keyData)- print("Opened session and persisted unlock key to keychain")+ print("Opened session and persisted Account Key to keychain")} else {print("Opened session in memory (keystore unavailable - device passcode not set, skipping keychain)")}@@ -62,22 +61,13 @@ extension VaultStore {}}- /*- * The stored key is the one secret a session holds; keychain and PIN only protect that same key. It is the- * Account Key, so it does not depend on the password: a typed password yields an unlock key (its Argon2id- * output), which opening the chain turns into the Account Key before anything stores it. A key stored before the- * account had a chain is an unlock key; it still opens the chain and is replaced by the Account Key on the next- * open. The Account Key opens the vault key and account private key, which are derived on demand and never- * stored.- */-/// Open a session with a key that opens the cached account key chain; the session keeps the Account Key it yields.- internal func openSession(unlockKey: Data) throws {- guard unlockKey.count == 32 else {+ 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.unlockKey = try openAccountKeyChain(with: unlockKey).accountKey+ self.accountKey = try openAccountKeyChain(with: key).accountKey}/// Store the key derivation parameters used for deriving the encryption key from the plain text password@@ -117,18 +107,17 @@ extension VaultStore {let vaultEncryptionKey: Data/// The account private key (JWK), nil when the account has no keypair or it does not open.let accountPrivateKey: String?- /// The key to store for later unlocks, in place of the key the chain was opened with.+ /// The Account Key to keep, in place of the key the chain was opened with.let accountKey: Data}- /// Open the cached account key chain with the stored key: the Account Key, or an unlock key that `accountKey` then- /// replaces (Rust `openAccountKeyChain`). Without a chain (account not yet upgraded) the unlock key is the vault key.- internal func openAccountKeyChain(with storedKey: Data) throws -> SessionKeys {+ /// Open the cached account key chain with the Account Key or the unlock key (Rust `openAccountKeyChain`).+ internal func openAccountKeyChain(with key: Data) throws -> SessionKeys {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: storedKey, accountPrivateKey: nil, accountKey: storedKey)+ return SessionKeys(vaultEncryptionKey: key, accountPrivateKey: nil, accountKey: key)}guard let encryptedVek = chain["encryptedVek"] as? String, !encryptedVek.isEmpty else {@@ -139,7 +128,7 @@ extension VaultStore {let encryptedPrivateKey = (chain["encryptedAccountPrivateKey"] as? String).flatMap { $0.isEmpty ? nil : $0 }do {let keys = try RustCoreFramework.openAccountKeyChain(- storedKey: storedKey, encryptedAccountKey: encryptedAccountKey, encryptedVek: encryptedVek, encryptedAccountPrivateKey: encryptedPrivateKey+ storedKey: key, encryptedAccountKey: encryptedAccountKey, encryptedVek: encryptedVek, encryptedAccountPrivateKey: encryptedPrivateKey)return SessionKeys(vaultEncryptionKey: keys.vaultEncryptionKey, accountPrivateKey: keys.accountPrivateKey, accountKey: keys.accountKey)} catch KeyChainError.UnlockKeyRejected {@@ -160,7 +149,7 @@ extension VaultStore {}/// Verify the password and return its unlock key (base64) if correct. Callers derive the SRP input from it for the- /// account's encryption type; `storeUnlockKey` turns it into the Account Key the session keeps.+ /// account's encryption type; `storeAccountKey` turns it into the Account Key.public func verifyPassword(_ password: String) -> String? {do {// Get encryption key derivation parameters@@ -215,7 +204,7 @@ extension VaultStore {let decryptedData = try AES.GCM.open(sealedBox, using: key)/*- * If the decryption succeeds, try to persist the unlock key of this session in the keychain.+ * If the decryption succeeds, try to persist the Account Key in the keychain.* This makes sure that on future password unlock attempts, only successful decryptions* will be remembered and used so failed re-authentication attempts won't overwrite* a previous successful decryption key stored in the keychain.@@ -223,9 +212,9 @@ extension VaultStore {* We only attempt this if Face ID is enabled AND keystore is available.* If keystore is not available (no device passcode), we silently skip this step.*/- if self.enabledAuthMethods.contains(.faceID) && isKeystoreAvailable(), let unlockKey = self.unlockKey {+ if self.enabledAuthMethods.contains(.faceID) && isKeystoreAvailable(), let accountKey = self.accountKey {do {- try storeKeyInKeychain(unlockKey)+ try storeKeyInKeychain(accountKey)} catch {// Don't fail the decryption if we can't store to keychain// This can happen if device passcode is removed after Face ID was enabled@@ -272,31 +261,30 @@ extension VaultStore {/// Get the encryption key - the key used to encrypt and decrypt the vault.internal func getEncryptionKey() throws -> Data {- let storedKey = try getUnlockKey()- let keys = try openAccountKeyChain(with: storedKey)- if keys.accountKey != storedKey {- // The session held an unlock key and the account has a key chain since (a sync accepted one created on- // another device): keep the Account Key from now on.- self.unlockKey = keys.accountKey- convertLegacyKeychainKey(keychainKey: storedKey, accountKey: keys.accountKey)+ let key = try getAccountKey()+ let keys = try openAccountKeyChain(with: key)+ if keys.accountKey != key {+ // A legacy key, see `VaultStore+LegacyKeyConversion`.+ self.accountKey = keys.accountKey+ convertLegacyKeychainKey(keychainKey: key, accountKey: keys.accountKey)}return keys.vaultEncryptionKey}- /// Get the session's stored key, which the keychain and PIN protect.- internal func getUnlockKey() throws -> Data {- if let key = self.unlockKey {+ /// Get the Account Key, opening the session from the keychain when none is in memory.+ internal func getAccountKey() throws -> Data {+ if let key = self.accountKey {return key}try openSessionFromKeychain()- guard let key = self.unlockKey else {+ guard let key = self.accountKey else {throw AppError.keystoreKeyNotFound}return key}- /// Open a session with the unlock key the keychain holds, behind a biometric prompt.+ /// Open a session with the Account Key the keychain holds, behind a biometric prompt.private func openSessionFromKeychain() throws {// Key not in memory - check if we should try keychain retrieval// Only attempt keychain retrieval if Face ID is enabled AND keystore is available@@ -337,15 +325,15 @@ extension VaultStore {}do {- try openSession(unlockKey: keyData)- if let accountKey = self.unlockKey {+ try openSession(with: keyData)+ if let accountKey = self.accountKey {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)")+ print("The Account Key from the keychain does not open the account key chain: \(vaultError.message)")throw vaultError} catch {- print("The unlock key from the keychain does not open the account key chain: \(error)")+ print("The Account Key from the keychain does not open the account key chain: \(error)")throw AppError.unlockKeyRejected}return@@ -396,7 +384,7 @@ extension VaultStore {return status == errSecSuccess}- /// Store the unlock key in the keychain+ /// Store the Account Key in the keychaininternal func storeKeyInKeychain(_ keyData: Data) throws {// Check if keystore is available (device passcode must be set)guard isKeystoreAvailable() else {@@ -418,7 +406,7 @@ extension VaultStore {let query: [String: Any] = [kSecClass as String: kSecClassGenericPassword,kSecAttrService as String: VaultConstants.keychainService,- kSecAttrAccount as String: VaultConstants.unlockKeyKey,+ kSecAttrAccount as String: VaultConstants.accountKeyKey,kSecAttrAccessGroup as String: VaultConstants.keychainAccessGroup,kSecValueData as String: keyData,kSecAttrAccessControl as String: accessControl@@ -437,7 +425,7 @@ extension VaultStore {let query: [String: Any] = [kSecClass as String: kSecClassGenericPassword,kSecAttrService as String: VaultConstants.keychainService,- kSecAttrAccount as String: VaultConstants.unlockKeyKey,+ kSecAttrAccount as String: VaultConstants.accountKeyKey,kSecAttrAccessGroup as String: VaultConstants.keychainAccessGroup]@@ -449,7 +437,7 @@ extension VaultStore {// MARK: - Private Keychain Methods- /// Retrieve the unlock key from the keychain+ /// Retrieve the Account Key from the keychainprivate func retrieveKeyFromKeychain(context: LAContext) throws -> Data {// Ensure interaction is allowed so system can prompt for biometric authenticationcontext.interactionNotAllowed = false@@ -462,7 +450,7 @@ extension VaultStore {let query: [String: Any] = [kSecClass as String: kSecClassGenericPassword,kSecAttrService as String: VaultConstants.keychainService,- kSecAttrAccount as String: VaultConstants.unlockKeyKey,+ kSecAttrAccount as String: VaultConstants.accountKeyKey,kSecAttrAccessGroup as String: VaultConstants.keychainAccessGroup,kSecReturnData as String: true,kSecUseAuthenticationContext as String: context,diff --git a/apps/mobile-app/ios/VaultStoreKit/VaultStore+LegacyKeyConversion.swift b/apps/mobile-app/ios/VaultStoreKit/VaultStore+LegacyKeyConversion.swiftindex d4b19bc57..eda78e566 100644--- a/apps/mobile-app/ios/VaultStoreKit/VaultStore+LegacyKeyConversion.swift+++ b/apps/mobile-app/ios/VaultStoreKit/VaultStore+LegacyKeyConversion.swift@@ -2,9 +2,10 @@ 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.+/// 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.////// TODO: remove once accounts without a key chain (pre-0.31.0) are no longer supported.extension VaultStore {diff --git a/apps/mobile-app/ios/VaultStoreKit/VaultStore+Pin.swift b/apps/mobile-app/ios/VaultStoreKit/VaultStore+Pin.swiftindex 0277261d0..9d0fb4f14 100644--- a/apps/mobile-app/ios/VaultStoreKit/VaultStore+Pin.swift+++ b/apps/mobile-app/ios/VaultStoreKit/VaultStore+Pin.swift@@ -53,13 +53,13 @@ extension VaultStore {throw AppError.biometricNotAvailable}- // 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)+ // The PIN protects the Account Key (vault must be unlocked), never the vault key+ try encryptKeyWithPin(try getAccountKey(), 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 {+ /// Encrypt the Account Key with a key derived from the PIN and keep it in the keychain.+ internal func encryptKeyWithPin(_ accountKey: Data, pin: String) throws {// Generate random saltvar salt = Data(count: 16)let result = salt.withUnsafeMutableBytes {@@ -72,9 +72,9 @@ extension VaultStore {// Derive key from PIN + salt using Argon2idlet pinKey = try derivePinKey(pin: pin, salt: salt)- // Encrypt the unlock key using AES-GCM+ // Encrypt the Account Key using AES-GCMlet symmetricKey = SymmetricKey(data: pinKey)- let sealedBox = try AES.GCM.seal(unlockKey, using: symmetricKey)+ let sealedBox = try AES.GCM.seal(accountKey, using: symmetricKey)guard let encryptedData = sealedBox.combined else {throw NSError(domain: "VaultStore", code: 23, userInfo: [NSLocalizedDescriptionKey: "Failed to encrypt vault key"])}@@ -94,7 +94,7 @@ extension VaultStore {// MARK: - PIN Unlock Methods/// Unlock with PIN- /// Returns the decrypted stored key+ /// Returns the Account Key////// - Parameter pin: The PIN to use for unlocking/// - Returns: The decrypted key (base64), to open the session withdiff --git a/apps/mobile-app/ios/VaultStoreKit/VaultStore+PublicKeyCrypto.swift b/apps/mobile-app/ios/VaultStoreKit/VaultStore+PublicKeyCrypto.swiftindex a12cc87c0..6b651bc0a 100644--- a/apps/mobile-app/ios/VaultStoreKit/VaultStore+PublicKeyCrypto.swift+++ b/apps/mobile-app/ios/VaultStoreKit/VaultStore+PublicKeyCrypto.swift@@ -3,17 +3,14 @@ import Security/// Extension for the VaultStore class to handle RSA public key encryptionextension VaultStore {- /// Encrypts the session's stored key using an RSA public key for mobile login+ /// Encrypts the Account Key using an RSA public key for mobile login/// The receiving client opens the account key chain with it./// - Parameter publicKeyJWK: The RSA public key in JWK format (JSON string)- /// - Returns: The encrypted unlock key- public func encryptUnlockKeyForMobileLogin(publicKeyJWK: String) throws -> Data {- // Get the unlock key from the vault store- // This will only work if the vault is unlocked (unlock key is in memory)- let unlockKey = try getUnlockKey()-- // Encrypt the unlock key with the provided public key- return try encryptWithPublicKey(data: unlockKey, publicKeyJWK: publicKeyJWK)+ /// - Returns: The encrypted Account Key+ public func encryptAccountKeyForMobileLogin(publicKeyJWK: String) throws -> Data {+ // Only works while the vault is unlocked (Account Key in memory)+ let accountKey = try getAccountKey()+ return try encryptWithPublicKey(data: accountKey, publicKeyJWK: publicKeyJWK)}/// Encrypts data using an RSA public keydiff --git a/apps/mobile-app/ios/VaultStoreKit/VaultStore.swift b/apps/mobile-app/ios/VaultStoreKit/VaultStore.swiftindex 2126379b0..b6e44e283 100644--- a/apps/mobile-app/ios/VaultStoreKit/VaultStore.swift+++ b/apps/mobile-app/ios/VaultStoreKit/VaultStore.swift@@ -32,26 +32,25 @@ public class VaultStore {/// The live vault, held in the Rust core's memory. Nil while vault is locked.internal var dbConnection: SqliteMemoryDatabase?- /// The stored key: the one secret the unlocked session holds in memory, and the key the unlock methods (keychain,- /// PIN) protect. Every other key is derived from it and the cached account key chain.- internal var unlockKey: Data?+ /// The Account Key the unlocked session holds and the keychain and PIN protect (see `VaultStore+LegacyKeyConversion`).+ internal var accountKey: Data?- /// The encryption key for the vault, derived from the unlock key. Nil while the vault is locked.+ /// The encryption key for the vault, derived from the Account Key. Nil while the vault is locked.internal var encryptionKey: Data? {return sessionKeys?.vaultEncryptionKey}- /// The account private key (JWK) of the unlocked session, derived from the unlock key.+ /// The account private key (JWK) of the unlocked session, derived from the Account Key.internal var accountPrivateKey: String? {return sessionKeys?.accountPrivateKey}- /// What the stored key opens in the cached account key chain.+ /// What the Account Key opens in the cached account key chain.private var sessionKeys: SessionKeys? {- guard let unlockKey = unlockKey else {+ guard let accountKey = accountKey else {return nil}- return try? openAccountKeyChain(with: unlockKey)+ return try? openAccountKeyChain(with: accountKey)}/// Last successful biometric/PIN auth operation.diff --git a/apps/mobile-app/ios/VaultStoreKitTests/VaultStoreKitTests.swift b/apps/mobile-app/ios/VaultStoreKitTests/VaultStoreKitTests.swiftindex 6a626a5ea..a92374763 100644--- a/apps/mobile-app/ios/VaultStoreKitTests/VaultStoreKitTests.swift+++ b/apps/mobile-app/ios/VaultStoreKitTests/VaultStoreKitTests.swift@@ -3,14 +3,14 @@ import XCTestfinal public class VaultStoreKitTests: XCTestCase {var vaultStore: VaultStore!- let testUnlockKeyBase64 = "/9So3C83JLDIfjsF0VQOc4rz1uAFtIseW7yrUuztAD0=" // 32 bytes for AES-256+ let testAccountKeyBase64 = "/9So3C83JLDIfjsF0VQOc4rz1uAFtIseW7yrUuztAD0=" // 32 bytes for AES-256override public func setUp() {super.setUp()vaultStore = VaultStore.shareddo {- try vaultStore.storeUnlockKey(base64Key: testUnlockKeyBase64)+ try vaultStore.storeAccountKey(base64Key: testAccountKeyBase64)let encryptedDb = try loadTestDatabase()try vaultStore.storeEncryptedDatabase(encryptedDb)diff --git a/apps/mobile-app/ios/VaultUtils/VaultConstants.swift b/apps/mobile-app/ios/VaultUtils/VaultConstants.swiftindex fff068d18..9c9285212 100644--- a/apps/mobile-app/ios/VaultUtils/VaultConstants.swift+++ b/apps/mobile-app/ios/VaultUtils/VaultConstants.swift@@ -8,7 +8,7 @@ public struct VaultConstants {public static let userDefaultsSuite = "group.net.aliasvault.autofill"public static let vaultMetadataKey = "aliasvault_vault_metadata"- public static let unlockKeyKey = "aliasvault_encryption_key"+ public static let accountKeyKey = "aliasvault_encryption_key"public static let encryptedDbFileName = "encrypted_db.sqlite"public static let authMethodsKey = "aliasvault_auth_methods"public static let autoLockTimeoutKey = "aliasvault_auto_lock_timeout"diff --git a/apps/mobile-app/specs/NativeVaultManager.ts b/apps/mobile-app/specs/NativeVaultManager.tsindex dedd8c4e0..4372b05cd 100644--- a/apps/mobile-app/specs/NativeVaultManager.ts+++ b/apps/mobile-app/specs/NativeVaultManager.ts@@ -64,9 +64,9 @@ export interface Spec extends TurboModule {// Database/encryption key operationsstoreMetadata(metadata: string): Promise<void>;setAuthMethods(authMethods: string[]): Promise<void>;- storeUnlockKeyInMemory(base64UnlockKey: string): Promise<void>;+ storeAccountKeyInMemory(base64Key: string): Promise<void>;clearEncryptionKeyFromMemory(): Promise<void>;- storeUnlockKey(base64UnlockKey: string): Promise<void>;+ storeAccountKey(base64Key: string): Promise<void>;storeUnlockKeyDerivationParams(keyDerivationParams: string): Promise<void>;getUnlockKeyDerivationParams(): Promise<string | null>;getAccountKeyChain(): Promise<string | null>;@@ -140,7 +140,7 @@ export interface Spec extends TurboModule {showPasswordUnlock(title: string | null, subtitle: string | null, buttonText: string | null): Promise<boolean | null>;// Mobile login methods- encryptUnlockKeyForMobileLogin(publicKeyJWK: string): Promise<string>;+ encryptAccountKeyForMobileLogin(publicKeyJWK: string): Promise<string>;// Re-authentication methods// Authenticate user with biometric or PIN. If title/subtitle are null/empty, defaults to "Unlock Vault" context.diff --git a/apps/mobile-app/utils/SqliteClient.ts b/apps/mobile-app/utils/SqliteClient.tsindex d827dafb5..337223f1e 100644--- a/apps/mobile-app/utils/SqliteClient.ts+++ b/apps/mobile-app/utils/SqliteClient.ts@@ -182,31 +182,30 @@ class SqliteClient {}/**- * Open a session in memory with the unlock key or a stored Account Key, without keychain persistence.+ * 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.*- * @param base64UnlockKey The base64 encoded unlock key+ * @param base64Key The base64 encoded unlock key or Account Key*/- public async storeUnlockKeyInMemory(base64UnlockKey: string): Promise<void> {+ public async storeAccountKeyInMemory(base64Key: string): Promise<void> {try {- await NativeVaultManager.storeUnlockKeyInMemory(base64UnlockKey);+ await NativeVaultManager.storeAccountKeyInMemory(base64Key);} catch (error) {- console.error('Error storing unlock key in memory:', error);+ console.error('Error storing Account Key in memory:', error);throw error;}}/**- * Open a session with the unlock key or a stored Account Key AND persist the Account Key to keychain (may trigger biometric prompt).+ * Open a session with the unlock key or the Account Key AND persist the Account Key to keychain (may trigger biometric prompt).*- * @param base64UnlockKey The base64 encoded unlock key+ * @param base64Key The base64 encoded unlock key or Account Key*/- public async storeUnlockKey(base64UnlockKey: string): Promise<void> {+ public async storeAccountKey(base64Key: string): Promise<void> {try {- // Open the session with the unlock key in the native module- await NativeVaultManager.storeUnlockKey(base64UnlockKey);+ await NativeVaultManager.storeAccountKey(base64Key);} catch (error) {- console.error('Error storing unlock key:', error);+ console.error('Error storing Account Key:', error);throw error;}}diff --git a/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Auth/PasswordChangeRequest.cs b/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Auth/PasswordChangeRequest.csindex d62501816..4e9636b5c 100644--- a/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Auth/PasswordChangeRequest.cs+++ b/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Auth/PasswordChangeRequest.cs@@ -9,7 +9,7 @@ namespace AliasVault.Shared.Models.WebApi.V2.Auth;/// <summary>/// Request for POST /v2/Auth/change-password. Carries the new SRP credentials plus the Account Key-/// re-encrypted with the new password-derived KEK.+/// re-encrypted with the KEK derived from the new password's unlock key./// </summary>public class PasswordChangeRequest{@@ -19,7 +19,7 @@ public class PasswordChangeRequest/// <summary>Gets or sets the client's session proof for the SRP proof of the current password.</summary>public required string CurrentClientSessionProof { get; set; }- /// <summary>Gets or sets the new SRP/KEK derivation salt.</summary>+ /// <summary>Gets or sets the new unlock key derivation salt.</summary>public required string NewPasswordSalt { get; set; }/// <summary>Gets or sets the new SRP verifier.</summary>@@ -29,9 +29,9 @@ public class PasswordChangeRequest/// account keypair and grants are untouched by a password change.</summary>public required string NewEncryptedAccountKey { get; set; }- /// <summary>Gets or sets the KDF type the client derived the new KEK with (currently always Argon2Id).</summary>+ /// <summary>Gets or sets the KDF type the client derived the new unlock key with.</summary>public required string NewEncryptionType { get; set; }- /// <summary>Gets or sets the KDF settings JSON the client derived the new KEK with.</summary>+ /// <summary>Gets or sets the KDF settings JSON the client derived the new unlock key with.</summary>public required string NewEncryptionSettings { get; set; }}diff --git a/apps/web/src/components/settings/security/QuickVaultUnlockSection.tsx b/apps/web/src/components/settings/security/QuickVaultUnlockSection.tsxindex 653303164..96b06962a 100644--- a/apps/web/src/components/settings/security/QuickVaultUnlockSection.tsx+++ b/apps/web/src/components/settings/security/QuickVaultUnlockSection.tsx@@ -23,7 +23,7 @@ const QuickVaultUnlockSection = forwardRef<SectionHandle>((_, ref) => {useImperativeHandle(ref, () => ({ loadData }), [loadData]);/**- * Create a passkey and encrypt the session keys with it.+ * Create a passkey and encrypt the Account Key with it.*/const enable = async (): Promise<void> => {try {diff --git a/apps/web/src/pages/auth/Login.tsx b/apps/web/src/pages/auth/Login.tsxindex 99d64e47a..525c4f9a4 100644--- a/apps/web/src/pages/auth/Login.tsx+++ b/apps/web/src/pages/auth/Login.tsx@@ -110,7 +110,7 @@ const Login: React.FC = () => {};/**- * Store the tokens and the unlock key, then continue to the sync page which loads the vault.+ * Store the tokens and the Account Key, then continue to the sync page which loads the vault.*/const completeLogin = async (loginUsername: string, accessToken: string, refreshToken: string, unlockKey: string, params: UnlockKeyDerivationParams): Promise<void> => {isCompletingLogin.current = true;@@ -118,16 +118,16 @@ const Login: React.FC = () => {await auth.setAuthTokens(SrpAuthService.normalizeUsername(loginUsername), accessToken, refreshToken);// Fetch the key chain, check the unlock key opens it and cache it; the vault key is derived from the two on demand.- let storedKey: string;+ let accountKey: string;try {- storedKey = await VaultKeyService.refreshKeyChain(unlockKey, webApi);+ accountKey = await VaultKeyService.refreshKeyChain(unlockKey, webApi);} catch (err) {// Without a usable key chain the session is useless; end it so the error shows on this form.await auth.logout();throw err;}await vaultStore.storeUnlockKeyDerivationParams(params);- await vaultStore.storeUnlockKey(storedKey);+ await vaultStore.storeAccountKey(accountKey);notifications.clearMessages();navigate('/sync', { replace: true });@@ -148,7 +148,7 @@ const Login: React.FC = () => {};/**- * Finish a login the mobile app approved: the mobile app sends the unlock key.+ * Finish a login the mobile app approved: the mobile app sends its Account Key.*/const handleMobileLoginSuccess = async (result: MobileLoginResult): Promise<void> => {showLoading(t('auth.loggingIn'));@@ -189,7 +189,7 @@ const Login: React.FC = () => {return;}- await processLoginVerify(validateLoginResponse, prepared.passwordHashBase64, response);+ await processLoginVerify(validateLoginResponse, prepared.unlockKeyBase64, response);} catch (err) {setErrors(await toErrorMessages(err));} finally {@@ -214,7 +214,7 @@ const Login: React.FC = () => {throw new Error(t('common.errors.invalidCode'));}const validateLoginResponse = await srpUtil.validateLogin2Fa(username, credentials, rememberMe || rememberMachine, loginResponse, parseInt(code, 10));- await processLoginVerify(validateLoginResponse, credentials.passwordHashBase64, loginResponse);+ await processLoginVerify(validateLoginResponse, credentials.unlockKeyBase64, loginResponse);} catch (err) {setErrors(await toErrorMessages(err));} finally {@@ -235,7 +235,7 @@ const Login: React.FC = () => {throw new Error(t('auth.loginForm.loginRequestErrorMessage'));}const validateLoginResponse = await srpUtil.validateLoginRecoveryCode(username, credentials, rememberMe, loginResponse, recoveryCode.trim());- await processLoginVerify(validateLoginResponse, credentials.passwordHashBase64, loginResponse);+ await processLoginVerify(validateLoginResponse, credentials.unlockKeyBase64, loginResponse);} catch (err) {setErrors(await toErrorMessages(err));} finally {diff --git a/apps/web/src/pages/auth/Unlock.tsx b/apps/web/src/pages/auth/Unlock.tsxindex 6ff6a570a..71fb3c72f 100644--- a/apps/web/src/pages/auth/Unlock.tsx+++ b/apps/web/src/pages/auth/Unlock.tsx@@ -59,7 +59,7 @@ const Unlock: React.FC = () => {const username = auth.username;/**- * Decrypt the unlock key with the passkey and open the vault.+ * Decrypt the Account Key with the passkey and open the vault.*/const unlockWithWebAuthn = useCallback(async (): Promise<void> => {if (!WebAuthnService.isEnabled()) {@@ -161,24 +161,24 @@ const Unlock: React.FC = () => {setErrors([]);try {- let unlockKey: string;+ let accountKey: string;if (dbContext.getIsOffline()) {const params = await MasterPasswordService.getStoredDerivationParams();if (!params) {throw new Error(t('auth.unlockPage.connectionFailedError'));}- const prepared = await SrpAuthService.prepareCredentials(password, params.salt, params.encryptionType, params.encryptionSettings);+ const unlockKey = await SrpAuthService.deriveUnlockKey(password, params.salt, params.encryptionSettings);// Throws an unlock-key-rejected (E-206) error on a wrong password.- unlockKey = await VaultKeyService.verifyUnlockKey(prepared.passwordHashBase64);+ accountKey = await VaultKeyService.verifyUnlockKey(unlockKey);} else {const loginResponse = await srpUtil.initiateLogin(username);- const prepared = await SrpAuthService.prepareCredentials(password, loginResponse.salt, loginResponse.encryptionType, loginResponse.encryptionSettings);+ const unlockKey = await SrpAuthService.deriveUnlockKey(password, loginResponse.salt, loginResponse.encryptionSettings);await vaultStore.storeUnlockKeyDerivationParams({ salt: loginResponse.salt, encryptionType: loginResponse.encryptionType, encryptionSettings: loginResponse.encryptionSettings });// Throws an unlock-key-rejected (E-206) error on a wrong password.- unlockKey = await VaultKeyService.refreshKeyChain(prepared.passwordHashBase64, webApi);+ accountKey = await VaultKeyService.refreshKeyChain(unlockKey, webApi);}- await vaultStore.storeUnlockKey(unlockKey);+ await vaultStore.storeAccountKey(accountKey);navigate('/sync', { replace: true });} catch (err) {console.error('Unlock error:', err);@@ -198,7 +198,7 @@ const Unlock: React.FC = () => {};/**- * Replace the session with the one the mobile app approved and open the vault with the unlock key it sent.+ * Replace the session with the one the mobile app approved and open the vault with the key it sent.*/const handleMobileUnlockSuccess = async (result: MobileLoginResult): Promise<void> => {showLoading(t('app.status.unlockingVault'));@@ -217,9 +217,9 @@ 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.- const storedKey = await VaultKeyService.refreshKeyChain(result.unlockKey, webApi);+ const accountKey = await VaultKeyService.refreshKeyChain(result.unlockKey, webApi);await vaultStore.storeUnlockKeyDerivationParams({ salt: result.salt, encryptionType: result.encryptionType, encryptionSettings: result.encryptionSettings });- await vaultStore.storeUnlockKey(storedKey);+ await vaultStore.storeAccountKey(accountKey);navigate('/sync', { replace: true });} catch (err) {console.error('Mobile unlock error:', err);diff --git a/apps/web/src/services/RegistrationService.ts b/apps/web/src/services/RegistrationService.tsindex 17c976f0c..2ea92942a 100644--- a/apps/web/src/services/RegistrationService.ts+++ b/apps/web/src/services/RegistrationService.ts@@ -22,6 +22,6 @@ export const RegistrationService = {await setAuthTokens(registered.username, registered.token.token, registered.token.refreshToken);await VaultKeyService.cacheVaultKeyBlobs({ type: UnlockMethodType.Password, ...registered.keys.accountKeys, ...registered.derivationParams });await vaultStore.storeUnlockKeyDerivationParams(registered.derivationParams);- await vaultStore.storeUnlockKey(registered.derivedKey);+ await vaultStore.storeAccountKey(registered.derivedKey);},};diff --git a/apps/web/src/utils/LegacyStorageCleanup.ts b/apps/web/src/utils/LegacyStorageCleanup.tsindex 762e495b7..58e44cf25 100644--- a/apps/web/src/utils/LegacyStorageCleanup.ts+++ b/apps/web/src/utils/LegacyStorageCleanup.ts@@ -3,9 +3,9 @@ import { getLocalPreference, removeLocalPreference, setLocalPreference } from '@import { LocalPreferenceKeys } from '@/utils/StorageKeys';/**- * localStorage keys only the previous (Blazor) web client wrote: its tokens, its cached key chain, debug keys, its- * passkey unlock (which held the password-derived key; passkey unlock is set up again in this app) and its own- * language key. This app keeps its session in IndexedDB, so none of them is read any more.+ * localStorage keys no current client reads: the previous (Blazor) web client's tokens, cached key chain, debug keys+ * and language key, plus the passkey unlock keys both web clients wrote before 0.31.0 (which held the unlock key;+ * passkey unlock is set up again under new keys).*/const LEGACY_ONLY_KEYS = ['token',diff --git a/apps/web/src/utils/MasterPasswordCheck.ts b/apps/web/src/utils/MasterPasswordCheck.tsindex 973300084..94ac88766 100644--- a/apps/web/src/utils/MasterPasswordCheck.ts+++ b/apps/web/src/utils/MasterPasswordCheck.ts@@ -15,9 +15,9 @@ export async function verifyMasterPassword(password: string): Promise<boolean> {throw new Error('No local key chain to verify the master password against');}- const prepared = await SrpAuthService.prepareCredentials(password, params.salt, params.encryptionType, params.encryptionSettings);+ const unlockKey = await SrpAuthService.deriveUnlockKey(password, params.salt, params.encryptionSettings);try {- await VaultKeyService.verifyUnlockKey(prepared.passwordHashBase64);+ await VaultKeyService.verifyUnlockKey(unlockKey);return true;} catch (error) {const code = error instanceof Error ? extractErrorCode(error.message) : null;diff --git a/apps/web/src/utils/WebAuthnService.ts b/apps/web/src/utils/WebAuthnService.tsindex b41cbd4df..ab5c30fc3 100644--- a/apps/web/src/utils/WebAuthnService.ts+++ b/apps/web/src/utils/WebAuthnService.ts@@ -115,7 +115,7 @@ async function createCredentialDerivedKey(username: string): Promise<{ credentia}/**- * Passkey quick unlock: the session's Account Key encrypted with a key the passkey derives, kept in localStorage.+ * Passkey quick unlock: the Account Key encrypted with a key the passkey derives, kept in localStorage.*/export const WebAuthnService = {/**@@ -126,10 +126,10 @@ export const WebAuthnService = {},/**- * Create a passkey and encrypt the session's Account Key with it.+ * Create a passkey and encrypt the Account Key with it.*/async enable(username: string): Promise<void> {- const accountKey = await VaultKeyService.getSessionUnlockKey();+ const accountKey = await VaultKeyService.getSessionAccountKey();if (!accountKey) {throw new Error('Vault is locked');}@@ -171,6 +171,6 @@ export const WebAuthnService = {}throw error;}- await getPlatform().storage.set(StorageKeys.UNLOCK_KEY, accountKey);+ await getPlatform().storage.set(StorageKeys.ACCOUNT_KEY, accountKey);},};diff --git a/apps/web/src/vault/VaultStore.ts b/apps/web/src/vault/VaultStore.tsindex 077d49c78..cda37a8bd 100644--- a/apps/web/src/vault/VaultStore.ts+++ b/apps/web/src/vault/VaultStore.ts@@ -1,5 +1,5 @@/**- * The web app's vault store: the at-rest (encrypted) vault, the session key, and the interface with the Rust sync engine.+ * The web app's vault store: the at-rest (encrypted) vault, the Account Key, and the interface with the Rust sync engine.*/import { AppErrorCode, formatErrorWithCode } from '@aliasvault/client/api/errors/AppErrorCodes';@@ -81,7 +81,7 @@ function cleanupCachedSqliteClient(): void {}/**- * The session vault key, derived from the session unlock key and the cached key chain, or null while locked.+ * The session vault key, derived from the Account Key and the cached key chain, or null while locked.*/async function getEncryptionKey(): Promise<string | null> {return VaultKeyService.getSessionVaultEncryptionKey();@@ -372,11 +372,11 @@ export const vaultStore = {createVaultSqliteClient,/**- * Store the session unlock key.- * @param unlockKey - the unlock key+ * Store the Account Key.+ * @param accountKey - the Account Key*/- async storeUnlockKey(unlockKey: string): Promise<void> {- await getPlatform().storage.set(StorageKeys.UNLOCK_KEY, unlockKey);+ async storeAccountKey(accountKey: string): Promise<void> {+ await getPlatform().storage.set(StorageKeys.ACCOUNT_KEY, accountKey);},/**@@ -432,9 +432,9 @@ export const vaultStore = {*/async checkAuthStatus(): Promise<{ isLoggedIn: boolean; isVaultLocked: boolean; hasStoredVault: boolean }> {const storage = getPlatform().storage;- const [username, accessToken, vaultData, unlockKey] = await Promise.all([storage.get<string>(StorageKeys.USERNAME), storage.get<string>(StorageKeys.ACCESS_TOKEN), getEncryptedVault(), VaultKeyService.getSessionUnlockKey()]);+ const [username, accessToken, vaultData, accountKey] = await Promise.all([storage.get<string>(StorageKeys.USERNAME), storage.get<string>(StorageKeys.ACCESS_TOKEN), getEncryptedVault(), VaultKeyService.getSessionAccountKey()]);const isLoggedIn = username !== null && accessToken !== null;- return { isLoggedIn, isVaultLocked: isLoggedIn && unlockKey === null, hasStoredVault: vaultData !== null };+ return { isLoggedIn, isVaultLocked: isLoggedIn && accountKey === null, hasStoredVault: vaultData !== null };},/**diff --git a/core/client/src/auth/LegacyKeyConversion.ts b/core/client/src/auth/LegacyKeyConversion.tsindex cf7c44fc7..e0845a42e 100644--- a/core/client/src/auth/LegacyKeyConversion.ts+++ b/core/client/src/auth/LegacyKeyConversion.ts@@ -13,11 +13,11 @@ import { getPlatform } from '../platform/ClientPlatform';/*** Store the Account Key in the session when the session still held an unlock key.- * @param sessionKey - the key the session held+ * @param storedKey - 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);+export async function convertLegacySessionKey(storedKey: string, accountKey: string): Promise<void> {+ if (accountKey !== storedKey) {+ await getPlatform().storage.set(StorageKeys.ACCOUNT_KEY, accountKey);}}diff --git a/core/client/src/auth/MasterPasswordService.ts b/core/client/src/auth/MasterPasswordService.tsindex 89ad79d8d..024ac0b3b 100644--- a/core/client/src/auth/MasterPasswordService.ts+++ b/core/client/src/auth/MasterPasswordService.ts@@ -91,7 +91,7 @@ export class MasterPasswordService {const srpIdentity = challenge.srpIdentity ?? SrpAuthService.normalizeUsername(username ?? '');const proof = await SrpAuthService.deriveClientProof(challenge.salt, srpIdentity, credentials.passwordHashString, challenge.serverEphemeral);- return { proof, unlockKeyBase64: credentials.passwordHashBase64, srpIdentity };+ return { proof, unlockKeyBase64: credentials.unlockKeyBase64, srpIdentity };}/**diff --git a/core/client/src/auth/SrpAuthService.ts b/core/client/src/auth/SrpAuthService.tsindex 06fac563c..821f3434e 100644--- a/core/client/src/auth/SrpAuthService.ts+++ b/core/client/src/auth/SrpAuthService.ts@@ -51,7 +51,7 @@ export type PreparedCredentials = {/** The SRP password hash (uppercase hex) for the account's encryption type. */passwordHashString: string;/** The unlock key (base64): the Argon2id output of the password. */- passwordHashBase64: string;+ unlockKeyBase64: string;/** Set when the account still has a legacy verifier, see {@link LegacySrpVerifierUpgrade}. */legacyVerifierUpgrade?: LegacySrpVerifierUpgrade;};@@ -252,6 +252,18 @@ export class SrpAuthService {return SrpAuthService.deriveClientSession(loginResponse.salt, srpIdentity, passwordHashString, loginResponse.serverEphemeral);}+ /**+ * Derive the unlock key (the Argon2id output, base64) from the password.+ *+ * @param password - The user's password+ * @param salt - The account's salt+ * @param encryptionSettings - The encryption settings JSON string+ * @returns The unlock key (base64)+ */+ public static async deriveUnlockKey(password: string, salt: string, encryptionSettings: string): Promise<string> {+ return bytesToBase64(await EncryptionUtility.deriveKeyFromPassword(password, salt, encryptionSettings));+ }+/*** Derive the unlock key from the password and the SRP password hash the account's encryption type makes from it.*@@ -262,11 +274,8 @@ export class SrpAuthService {* @returns The SRP password hash (hex) and the unlock key (base64)*/public static async prepareCredentials(password: string, salt: string, encryptionType: string, encryptionSettings: string): Promise<PreparedCredentials> {- const unlockKey = bytesToBase64(await EncryptionUtility.deriveKeyFromPassword(password, salt, encryptionSettings));- return {- passwordHashString: await SrpAuthService.srpPasswordHash(unlockKey, encryptionType),- passwordHashBase64: unlockKey,- };+ const unlockKeyBase64 = await SrpAuthService.deriveUnlockKey(password, salt, encryptionSettings);+ return { passwordHashString: await SrpAuthService.srpPasswordHash(unlockKeyBase64, encryptionType), unlockKeyBase64 };}/**@@ -289,8 +298,8 @@ export class SrpAuthService {* @returns The credentials to log in with*/public static async prepareLoginCredentials(password: string, loginResponse: LoginResponse, username: string): Promise<PreparedCredentials> {- const unlockKey = bytesToBase64(await EncryptionUtility.deriveKeyFromPassword(password, loginResponse.salt, loginResponse.encryptionSettings));- return SrpAuthService.loginCredentials(unlockKey, loginResponse, username);+ const unlockKeyBase64 = await SrpAuthService.deriveUnlockKey(password, loginResponse.salt, loginResponse.encryptionSettings);+ return SrpAuthService.loginCredentials(unlockKeyBase64, loginResponse, username);}/**@@ -302,10 +311,7 @@ export class SrpAuthService {* @returns The credentials to log in with*/public static async loginCredentials(unlockKeyBase64: string, loginResponse: LoginResponse, username: string): Promise<PreparedCredentials> {- const credentials: PreparedCredentials = {- passwordHashString: await SrpAuthService.srpPasswordHash(unlockKeyBase64, loginResponse.encryptionType),- passwordHashBase64: unlockKeyBase64,- };+ const credentials: PreparedCredentials = { passwordHashString: await SrpAuthService.srpPasswordHash(unlockKeyBase64, loginResponse.encryptionType), unlockKeyBase64 };if (loginResponse.encryptionType !== LEGACY_ENCRYPTION_TYPE) {return credentials;}@@ -336,7 +342,7 @@ export class SrpAuthService {const credentials = await SrpAuthService.prepareCredentials(password, salt, DEFAULT_ENCRYPTION.type, DEFAULT_ENCRYPTION.settings);const privateKey = await SrpAuthService.derivePrivateKey(salt, srpIdentity, credentials.passwordHashString);const verifier = await SrpAuthService.deriveVerifier(privateKey);- return { salt, verifier, encryptionType: DEFAULT_ENCRYPTION.type, encryptionSettings: DEFAULT_ENCRYPTION.settings, unlockKeyBase64: credentials.passwordHashBase64 };+ return { salt, verifier, encryptionType: DEFAULT_ENCRYPTION.type, encryptionSettings: DEFAULT_ENCRYPTION.settings, unlockKeyBase64: credentials.unlockKeyBase64 };}/**diff --git a/core/client/src/auth/VaultKeyService.ts b/core/client/src/auth/VaultKeyService.tsindex 6857894de..00b80c8c7 100644--- a/core/client/src/auth/VaultKeyService.ts+++ b/core/client/src/auth/VaultKeyService.ts@@ -24,14 +24,14 @@ export type FetchVaultKeyResult = {};/**- * The keys a stored key opens.+ * The keys the Account 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). */+ /** The Account Key, which the session stores for later unlocks. */accountKey: string;};@@ -63,7 +63,7 @@ export class VaultKeyService {* 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}).+ * @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(unlockKeyBase64: string, webApi?: WebApiService): Promise<string> {@@ -87,7 +87,7 @@ 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 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}).+ * @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(unlockKeyBase64: string): Promise<string> {@@ -121,24 +121,23 @@ export class VaultKeyService {}/**- * The stored key of this session (see {@link SessionKeys.accountKey}), or null when the vault is locked.+ * The Account Key of the unlocked session, 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;+ public static async getSessionAccountKey(): Promise<string | null> {+ return (await getPlatform().storage.get(StorageKeys.ACCOUNT_KEY)) as string | null;}/**- * 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.+ * 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).*/public static async getSessionKeys(): Promise<SessionKeys | null> {- const unlockKey = await VaultKeyService.getSessionUnlockKey();- if (!unlockKey) {+ const accountKey = await VaultKeyService.getSessionAccountKey();+ if (!accountKey) {return null;}- const keys = await VaultKeyService.openKeyChain(unlockKey);- await convertLegacySessionKey(unlockKey, keys.accountKey);+ const keys = await VaultKeyService.openKeyChain(accountKey);+ await convertLegacySessionKey(accountKey, keys.accountKey);return keys;}@@ -175,7 +174,7 @@ export class VaultKeyService {await getPlatform().storage.setMany([{ key: StorageKeys.ENCRYPTED_ACCOUNT_KEY, value: newEncryptedAccountKey },{ key: StorageKeys.UNLOCK_KEY_DERIVATION_PARAMS, value: derivationParams },- { key: StorageKeys.UNLOCK_KEY, value: accountKeyBase64 },+ { key: StorageKeys.ACCOUNT_KEY, value: accountKeyBase64 },]);}diff --git a/core/client/src/constants/StorageKeys.ts b/core/client/src/constants/StorageKeys.tsindex 2a8d93d55..e2205d565 100644--- a/core/client/src/constants/StorageKeys.ts+++ b/core/client/src/constants/StorageKeys.ts@@ -41,7 +41,7 @@ export const StorageKeys = {PRIVATE_EMAIL_DOMAINS: 'local:privateEmailDomains',/** Private email domains that are hidden from the domain picker. */HIDDEN_PRIVATE_EMAIL_DOMAINS: 'local:hiddenPrivateEmailDomains',- /** Argon2 parameters used to derive the KEK from the master password. */+ /** Argon2 parameters used to derive the unlock key from the master password. */UNLOCK_KEY_DERIVATION_PARAMS: 'local:encryptionKeyDerivationParams',/** The VEK encrypted with the Account Key, as returned by the server. */ENCRYPTED_VEK: 'local:encryptedVek',@@ -91,10 +91,10 @@ export const StorageKeys = {*//**- * The unlock key of the session: the account private key and vault encryption key are derived from it and the cached key chain on demand (see VaultKeyService).+ * The Account Key of the session, from which the vault encryption key and account private key are opened on demand (see VaultKeyService).* Session-only: it must never persist to disk. An additional unlock method (PIN) protects this same key.*/- UNLOCK_KEY: 'session:unlockKey',+ ACCOUNT_KEY: 'session:unlockKey',/** The sync hold record (reason + when it was taken) while an operation no sync may race runs; see VaultSyncHold. */VAULT_SYNC_HOLD: 'session:vaultSyncHold',} as const satisfies Record<string, StorageKey>;@@ -115,7 +115,7 @@ export const AUTH_STORAGE_KEYS: readonly StorageKey[] = [/** Keys that must not survive a vault lock: the unlock key. Hosts add anything they derive from decrypted data. */export const VAULT_LOCK_STORAGE_KEYS: readonly StorageKey[] = [- StorageKeys.UNLOCK_KEY,+ StorageKeys.ACCOUNT_KEY,];/**diff --git a/core/client/src/sync/VaultSync.ts b/core/client/src/sync/VaultSync.tsindex 006a377dc..240513157 100644--- a/core/client/src/sync/VaultSync.ts+++ b/core/client/src/sync/VaultSync.ts@@ -137,11 +137,11 @@ export class VaultSync {public async syncVaultWithServer(options: VaultSyncOptions = {}): Promise<FullVaultSyncResult> {try {const storage = getPlatform().storage;- const [username, accessToken, unlockKey] = await Promise.all([storage.get<string>(StorageKeys.USERNAME), storage.get<string>(StorageKeys.ACCESS_TOKEN), VaultKeyService.getSessionUnlockKey()]);+ const [username, accessToken, accountKey] = await Promise.all([storage.get<string>(StorageKeys.USERNAME), storage.get<string>(StorageKeys.ACCESS_TOKEN), VaultKeyService.getSessionAccountKey()]);if (username === null || accessToken === null) {return syncResult({ success: false });}- if (!unlockKey) {+ if (!accountKey) {return syncResult({ success: false, errorCode: AppErrorCode.VAULT_LOCKED });}@@ -228,7 +228,7 @@ export class VaultSync {*/public async migrateVaultManifest(): Promise<VaultManifestMigrationResult> {try {- if (!await VaultKeyService.getSessionUnlockKey()) {+ if (!await VaultKeyService.getSessionAccountKey()) {return { success: false, pushed: false, errorCode: AppErrorCode.VAULT_LOCKED };}if (await (await this.openVault()).requiresLegacySqliteBlobMigration()) {diff --git a/core/rust/src/crypto/key_chain.rs b/core/rust/src/crypto/key_chain.rsindex c9230d153..1336f91c7 100644--- a/core/rust/src/crypto/key_chain.rs+++ b/core/rust/src/crypto/key_chain.rs@@ -140,7 +140,7 @@ pub struct OpenedKeyChain {pub account_private_key: Option<Zeroizing<String>>,}-/// Open a key chain with a stored key, which is either the Account Key or an unlock key (see the module docs).+/// 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) {Ok(vek) => (Zeroizing::new(stored_key.to_string()), vek),@@ -219,7 +219,6 @@ mod tests {assert!(unwrap_key(&hierarchy.account_keys.encrypted_account_key, &derive_kek_base64(&unlock_key).unwrap()).is_ok());}-#[test]fn chain_opens_with_the_unlock_key_and_hands_back_the_account_key() {let unlock_key = generate_key_base64();diff --git a/core/rust/src/vault_sync/engine.rs b/core/rust/src/vault_sync/engine.rsindex 1f68ec1ec..00ff7a16b 100644--- a/core/rust/src/vault_sync/engine.rs+++ b/core/rust/src/vault_sync/engine.rs@@ -214,7 +214,7 @@ async fn run_sync_preflight(ctx: &mut Ctx) -> SyncResult<Preflight> {// A changed server salt means the password was changed elsewhere, which warrants a logout.assert_salt_unchanged(ctx, status.srp_salt.as_deref()).await?;- // The session key is the VEK (or a legacy account's KEK) by contract; the host resolved it at login. The one+ // The session key is the VEK (or a legacy account's unlock key) by contract; the host resolved it at login. The one// case the sync has to catch itself: this device holds no chain because the account was still legacy when it// logged in, and another device created the hierarchy since. That shows up as a revision change, so a pull// (or a push about to hit the server) is where it is checked.diff --git a/core/rust/src/vault_sync/errors.rs b/core/rust/src/vault_sync/errors.rsindex 2b5ba22bb..0494998c0 100644--- a/core/rust/src/vault_sync/errors.rs+++ b/core/rust/src/vault_sync/errors.rs@@ -133,7 +133,7 @@ pub enum SyncError {/// The account key opened, the vault encryption key under it did not.#[error("The account key does not open the vault encryption key: {0}")]KeyChainUnreadable(String),- /// The session key matches neither the server's KEK nor its VEK; only a re-login recovers.+ /// The session key opens neither the server's chain nor its VEK; only a re-login recovers.#[error("Vault encryption key out of sync with the server; log in again")]KeyOutOfSync,/// A server manifest or bucket failed its hash check or did not decrypt.@@ -170,6 +170,15 @@ pub enum SyncError {Other(String),}+impl From<crate::crypto::KeyChainError> for SyncError {+ fn from(error: crate::crypto::KeyChainError) -> Self {+ match error {+ crate::crypto::KeyChainError::UnlockKeyRejected => SyncError::UnlockKeyRejected,+ crate::crypto::KeyChainError::KeyChainUnreadable(message) => SyncError::KeyChainUnreadable(message),+ }+ }+}+impl SyncError {/// How the host reports this failure.pub fn failure(&self) -> Failure {diff --git a/core/rust/src/vault_sync/keys.rs b/core/rust/src/vault_sync/keys.rsindex a94c4411c..69fb6f4be 100644--- a/core/rust/src/vault_sync/keys.rs+++ b/core/rust/src/vault_sync/keys.rs@@ -8,7 +8,6 @@ use super::state::{self, Ctx};use super::types::{SharedManifestDto, VaultKeyGetResponse, VaultKeyResponse, ALGORITHM_RSA_OAEP_SHA256};use super::http;use crate::crypto;-use zeroize::Zeroizing;/// Whether this device holds a vault key.pub(crate) async fn has_local_vault_key(host: &Host) -> SyncResult<bool> {@@ -134,23 +133,12 @@ async fn clear_cached_chain(host: &Host) -> SyncResult<()> {Ok(())}-/// Walk a key chain with an unlock key or the stored Account Key, telling a key that does not open the account key-/// (wrong password) apart from a chain whose VEK does not open under its own account key. Returns the VEK and the-/// Account Key.-fn walk_chain(encrypted_account_key: &str, encrypted_vek: &str, unlock_key: &str) -> SyncResult<(Zeroizing<String>, Zeroizing<String>)> {- let opened = crypto::open_account_key_chain(unlock_key, encrypted_account_key, encrypted_vek, None).map_err(|error| match error {- crypto::KeyChainError::UnlockKeyRejected => SyncError::UnlockKeyRejected,- crypto::KeyChainError::KeyChainUnreadable(message) => SyncError::KeyChainUnreadable(message),- })?;- Ok((opened.vault_encryption_key, opened.account_key))-}-/// Open a key chain with an unlock key or the stored Account Key: the VEK becomes the session key and the private key/// is staged.async fn open_chain(ctx: &mut Ctx, encrypted_account_key: &str, encrypted_vek: &str, encrypted_private_key: Option<&str>, unlock_key: &str) -> SyncResult<()> {- let (vek, account_key) = walk_chain(encrypted_account_key, encrypted_vek, unlock_key)?;- ctx.set_encryption_key(vek.to_string());- stage_account_private_key(ctx, &account_key, encrypted_private_key).await;+ let opened = crypto::open_account_key_chain(unlock_key, encrypted_account_key, encrypted_vek, None)?;+ ctx.set_encryption_key(opened.vault_encryption_key.to_string());+ stage_account_private_key(ctx, &opened.account_key, encrypted_private_key).await;Ok(())}@@ -210,10 +198,10 @@ pub(crate) async fn accept_hierarchy_created_elsewhere(ctx: &mut Ctx) -> SyncRes// Hosts hold the unlock key and derive the vault key from the cached chain.let accepted: SyncResult<()> = async {- let (vek, account_key) = walk_chain(&vault_key.encrypted_account_key, &encrypted_vek, &session_key)?;+ let opened = crypto::open_account_key_chain(&session_key, &vault_key.encrypted_account_key, &encrypted_vek, None)?;cache_vault_key_blobs(&ctx.host, &vault_key).await?;- switch_to_vek(ctx, &session_key, &vek).await?;- stage_account_private_key(ctx, &account_key, vault_key.encrypted_account_private_key.as_deref()).await;+ switch_to_vek(ctx, &session_key, &opened.vault_encryption_key).await?;+ stage_account_private_key(ctx, &opened.account_key, vault_key.encrypted_account_private_key.as_deref()).await;Ok(())}.await;diff --git a/core/rust/src/vault_sync/tests/mod.rs b/core/rust/src/vault_sync/tests/mod.rsindex 498f4f861..958daef2c 100644--- a/core/rust/src/vault_sync/tests/mod.rs+++ b/core/rust/src/vault_sync/tests/mod.rs@@ -667,7 +667,7 @@ fn manifest_migration_generates_the_key_hierarchy_and_pushes() {let posts: Vec<_> = host.requests_to("Vault").into_iter().filter(|r| r.method == "POST").collect();let body = posts[0].body.as_ref().unwrap();assert!(body["migration"]["accountKeys"]["encryptedAccountKey"].is_string(), "the migration push carries the key hierarchy");- assert!(crypto::unwrap_key(body["migration"]["accountKeys"]["encryptedAccountKey"].as_str().unwrap(), &unlock_key).is_err(), "the legacy vault key is not the KEK");+ assert!(crypto::unwrap_key(body["migration"]["accountKeys"]["encryptedAccountKey"].as_str().unwrap(), &unlock_key).is_err(), "the legacy vault key does not wrap the Account Key directly");let opened = crypto::open_account_key_chain(&unlock_key, body["migration"]["accountKeys"]["encryptedAccountKey"].as_str().unwrap(), body["migration"]["accountKeys"]["encryptedVek"].as_str().unwrap(), None).unwrap();assert_eq!(*opened.vault_encryption_key, new_key);assert!(host.state.contains_key(state::ENCRYPTED_ACCOUNT_KEY));@@ -753,7 +753,7 @@ fn legacy_snapshot_of(conn: &rusqlite::Connection, unlock_key: &str, revision: i})}-/// A host as a client predating the manifest storage format leaves it: a sqlite blob under the KEK, no personal+/// A host as a client predating the manifest storage format leaves it: a sqlite blob under the unlock key, no personal/// manifest id and no revision baseline, against a server that still holds the account as a legacy vault.fn pre_format_session_host(unlock_key: &str, local_item: &str, server_item: &str) -> TestHost {let mut host = TestHost::new(unlock_key);@@ -849,7 +849,7 @@ fn vault_key_body(hierarchy: &crypto::AccountKeyHierarchy) -> Value {json!({ "vaultKey": { "type": "password", "encryptedAccountKey": blobs.encrypted_account_key, "encryptedVek": blobs.encrypted_vek, "accountPublicKey": blobs.account_public_key, "encryptedAccountPrivateKey": blobs.encrypted_account_private_key, "salt": "salt", "encryptionType": "Argon2Id", "encryptionSettings": "{}" } })}-/// The cross-device race: this device logged in while the account was legacy (no cached chain, KEK session), and+/// The cross-device race: this device logged in while the account was legacy (no cached chain, unlock key session), and/// another device created the hierarchy since. The pull accepts it, and the stored vault reaches the host/// together with the VEK it is now encrypted under.#[test]@@ -914,7 +914,7 @@ fn resolve_vault_key_opens_the_chain_with_a_stored_account_key() {/// A legacy account has no chain: the password-derived key is the vault key and any stale cached chain is dropped.#[test]-fn resolve_vault_key_keeps_the_kek_for_a_legacy_account() {+fn resolve_vault_key_keeps_the_unlock_key_for_a_legacy_account() {let unlock_key = crypto::generate_key_base64();let mut host = TestHost::new(&unlock_key);host.state.insert(state::ENCRYPTED_ACCOUNT_KEY.to_string(), json!("stale"));@@ -948,11 +948,11 @@ fn resolve_vault_key_opens_the_cached_chain_when_the_server_is_unreachable() {#[test]fn resolve_vault_key_refuses_a_key_that_does_not_open_the_chain() {let hierarchy = crypto::create_account_key_hierarchy(&crypto::generate_key_base64()).unwrap();- let wrong_kek = crypto::generate_key_base64();- let mut host = TestHost::new(&wrong_kek);+ let wrong_unlock_key = crypto::generate_key_base64();+ let mut host = TestHost::new(&wrong_unlock_key);host.respond("GET", "VaultKey/Password", vault_key_body(&hierarchy));- let result = host.drive(&SyncSession::new(&request("resolveVaultKey", &wrong_kek, false, 0)).unwrap());+ let result = host.drive(&SyncSession::new(&request("resolveVaultKey", &wrong_unlock_key, false, 0)).unwrap());assert_eq!(result["success"], false);assert_eq!(result["errorCode"], "E-206");@@ -974,10 +974,10 @@ fn resolve_vault_key_tells_an_unreadable_chain_apart_from_a_wrong_password() {assert_eq!(result["errorCode"], "E-207");}-/// The sync trusts the key it is given: a KEK handed to a device that caches the chain is not upgraded any more,+/// The sync trusts the key it is given: an unlock key handed to a device that caches the chain is not upgraded any more,/// so the run fails to open the vault instead of silently swapping keys. Resolving the key is the host's job.#[test]-fn a_kek_session_on_a_migrated_device_is_not_upgraded_by_the_sync() {+fn an_unlock_key_session_on_a_migrated_device_is_not_upgraded_by_the_sync() {let unlock_key = crypto::generate_key_base64();let hierarchy = crypto::create_account_key_hierarchy(&unlock_key).unwrap();let vek = hierarchy.vault_encryption_key.clone();diff --git a/core/rust/src/vault_sync/tests/unloaded_blobs.rs b/core/rust/src/vault_sync/tests/unloaded_blobs.rsindex 1f4911a7f..802330220 100644--- a/core/rust/src/vault_sync/tests/unloaded_blobs.rs+++ b/core/rust/src/vault_sync/tests/unloaded_blobs.rs@@ -220,8 +220,8 @@ fn a_save_that_changed_nothing_is_not_written_again() {fn a_key_migration_push_is_refused_while_a_personal_blob_is_not_loaded() {// The migration encrypts every personal blob again under the new key; one it has no bytes for would stay under// the old key and never open again. The vault stays dirty and the migration runs again once the blob loads.- let kek = crypto::generate_key_base64();- let mut host = TestHost::new(&kek);+ let unlock_key = crypto::generate_key_base64();+ let mut host = TestHost::new(&unlock_key);insert_item(&host.local, ITEM_ID, "Old item", PERSONAL_MANIFEST_ID);let now = crate::common::timestamp::now_vault_datetime();host.local.execute("INSERT INTO Attachments (ManifestId, Id, ItemId, Filename, Blob, BlobHash, CreatedAt, UpdatedAt, IsDeleted) VALUES (?, 'cccccccc-0000-4000-8000-000000000001', ?, 'passport.pdf', NULL, 'hash-of-a-blob-that-is-not-loaded', ?, ?, 0)", rusqlite::params![PERSONAL_MANIFEST_ID, ITEM_ID, now, now]).unwrap();@@ -233,11 +233,11 @@ fn a_key_migration_push_is_refused_while_a_personal_blob_is_not_loaded() {host.respond("POST", "Vault/blobs/missing", json!({ "missing": [] }));host.respond("POST", "Vault", json!({ "status": 0, "manifestRevisions": [{ "manifestId": PERSONAL_MANIFEST_ID, "revision": 4 }], "bucketRevisions": [], "missingBlobHashes": [] }));- let result = host.drive(&SyncSession::new(&request("migrateManifest", &kek, false, 0)).unwrap());+ let result = host.drive(&SyncSession::new(&request("migrateManifest", &unlock_key, false, 0)).unwrap());assert_eq!(result["pushed"], false, "{}", result);assert!(host.requests_to("Vault").iter().all(|r| r.method != "POST"), "nothing was written with the new key");- assert_eq!(host.vault_key, kek, "and the session keeps its key");+ assert_eq!(host.vault_key, unlock_key, "and the session keeps its key");}#[test]