Skip to content

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

Refactor encryption key to unlock key in naming and storage (#2159)

Leendert de Borst0d38e4540ad6
diff --git a/apps/browser-extension/src/entrypoints/background.ts b/apps/browser-extension/src/entrypoints/background.ts
index b146f104d..48a38e504 100644
--- a/apps/browser-extension/src/entrypoints/background.ts
+++ b/apps/browser-extension/src/entrypoints/background.ts
@@ -11,7 +11,7 @@ import { handleGetWebAuthnSettings, handleWebAuthnCreate, handleWebAuthnGet, han
import { handleOpenPopup, handlePopupWithItem, handleOpenPopupCreateCredential, handleToggleContextMenu } from '@/entrypoints/background/PopupMessageHandler';
import { handleStoreSavePromptState, handleGetSavePromptState, handleClearSavePromptState, handleStoreLastAutofilled, handleGetLastAutofilled, handleClearLastAutofilled } from '@/entrypoints/background/SavePromptStateHandler';
import { handleStoreTwoFactorState, handleGetTwoFactorState, handleClearTwoFactorState } from '@/entrypoints/background/TwoFactorStateHandler';
-import { handleCheckAuthStatus, handleClearPersistedFormValues, handleClearSession, handleClearVaultData, handleLockVault, handleGetFilteredItems, handleGetSearchItems, handleGetDefaultEmailDomain, handleGetDefaultIdentitySettings, handleGetEncryptionKey, handleGetEncryptionKeyDerivationParams, handleGetPasswordSettings, handleGeneratePassword, handleGetPersistedFormValues, handleGetVault, handleGetVaultMigrationStatus, handlePersistFormValues, handleStoreEncryptionKey, handleStoreEncryptionKeyDerivationParams, handleGetEncryptedVault, handleStoreEncryptedVault, handleGetSyncState, handleMarkVaultClean, handleMigrateVaultManifest, handleFullVaultSync, handleGroupCreateVault, handleGroupInviteMember, handleGroupRevokeAccess, handleCheckLoginDuplicate, handleSaveLoginCredential, handleAddUrlToCredential, handleIsUrlLinkedToCredential, handleGetLoginSaveSettings, handleSetLoginSaveEnabled, handleGetItemsWithTotp, handleSearchItemsWithTotp, handleGetTotpSecrets, handleGenerateTotpCode, handleSetRecentlySelected, handleGetRecentlySelected, handleRecordItemUsage } from '@/entrypoints/background/VaultMessageHandler';
+import { handleCheckAuthStatus, handleClearPersistedFormValues, handleClearSession, handleClearVaultData, handleLockVault, handleGetFilteredItems, handleGetSearchItems, handleGetDefaultEmailDomain, handleGetDefaultIdentitySettings, handleGetEncryptionKey, handleGetUnlockKeyDerivationParams, handleGetPasswordSettings, handleGeneratePassword, handleGetPersistedFormValues, handleGetVault, handleGetVaultMigrationStatus, handlePersistFormValues, handleStoreUnlockKey, handleStoreUnlockKeyDerivationParams, handleGetEncryptedVault, handleStoreEncryptedVault, handleGetSyncState, handleMarkVaultClean, handleMigrateVaultManifest, handleFullVaultSync, handleGroupCreateVault, handleGroupInviteMember, handleGroupRevokeAccess, handleCheckLoginDuplicate, handleSaveLoginCredential, handleAddUrlToCredential, handleIsUrlLinkedToCredential, handleGetLoginSaveSettings, handleSetLoginSaveEnabled, handleGetItemsWithTotp, handleSearchItemsWithTotp, handleGetTotpSecrets, handleGenerateTotpCode, handleSetRecentlySelected, handleGetRecentlySelected, handleRecordItemUsage } from '@/entrypoints/background/VaultMessageHandler';
import { LocalPreferencesService } from '@/utils/LocalPreferencesService';
import { onMessage, sendMessage } from "@/utils/messaging/ExtensionMessaging";
@@ -238,7 +238,7 @@ export default defineBackground({
onMessage('CHECK_AUTH_STATUS', () => handleCheckAuthStatus());
onMessage('GET_ENCRYPTION_KEY', ({ sender }) => isTrustedExtensionSender(sender) ? handleGetEncryptionKey() : null);
- onMessage('GET_ENCRYPTION_KEY_DERIVATION_PARAMS', () => handleGetEncryptionKeyDerivationParams());
+ onMessage('GET_UNLOCK_KEY_DERIVATION_PARAMS', () => handleGetUnlockKeyDerivationParams());
onMessage('GET_VAULT', () => handleGetVault());
onMessage('GET_FILTERED_ITEMS', ({ data }) => handleGetFilteredItems(data));
onMessage('GET_SEARCH_ITEMS', ({ data }) => handleGetSearchItems(data));
@@ -248,14 +248,14 @@ export default defineBackground({
onMessage('GET_PASSWORD_SETTINGS', () => handleGetPasswordSettings());
onMessage('GENERATE_PASSWORD', ({ data }) => handleGeneratePassword(data.settings));
- onMessage('STORE_ENCRYPTION_KEY', async ({ data, sender }) => {
+ onMessage('STORE_UNLOCK_KEY', async ({ data, sender }) => {
if (!isTrustedExtensionSender(sender)) {
return { success: false };
}
- const result = await handleStoreEncryptionKey(data);
+ const result = await handleStoreUnlockKey(data);
/*
- * Storing the encryption key means the vault just became unlocked; let content scripts
+ * Storing the unlock 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) {
@@ -263,7 +263,7 @@ export default defineBackground({
}
return result;
});
- onMessage('STORE_ENCRYPTION_KEY_DERIVATION_PARAMS', ({ data }) => handleStoreEncryptionKeyDerivationParams(data));
+ onMessage('STORE_UNLOCK_KEY_DERIVATION_PARAMS', ({ data }) => handleStoreUnlockKeyDerivationParams(data));
onMessage('GET_ENCRYPTED_VAULT', () => handleGetEncryptedVault());
onMessage('STORE_ENCRYPTED_VAULT', ({ data }) => handleStoreEncryptedVault(data));
diff --git a/apps/browser-extension/src/entrypoints/background/AutolockTimeoutHandler.ts b/apps/browser-extension/src/entrypoints/background/AutolockTimeoutHandler.ts
index c6170b906..f95dc905d 100644
--- a/apps/browser-extension/src/entrypoints/background/AutolockTimeoutHandler.ts
+++ b/apps/browser-extension/src/entrypoints/background/AutolockTimeoutHandler.ts
@@ -25,8 +25,8 @@ let shortTimeoutTimer: ReturnType<typeof setTimeout> | null = null;
*/
async function lockVaultDueToInactivity(): Promise<void> {
// Check if vault is still unlocked before locking
- const encryptionKey = await storage.getItem(StorageKeys.ENCRYPTION_KEY) as string | null;
- if (!encryptionKey) {
+ const unlockKey = await storage.getItem(StorageKeys.UNLOCK_KEY) as string | null;
+ if (!unlockKey) {
// Vault is already locked
return;
}
@@ -86,8 +86,8 @@ async function setAutoLockTimer(timeoutSeconds: number): Promise<void> {
*/
export async function initializeAutoLockAlarm(): Promise<void> {
// Check if vault is unlocked
- const encryptionKey = await storage.getItem(StorageKeys.ENCRYPTION_KEY) as string | null;
- if (!encryptionKey) {
+ const unlockKey = await storage.getItem(StorageKeys.UNLOCK_KEY) as string | null;
+ if (!unlockKey) {
// Vault is locked, clear any existing alarm
clearShortTimeoutTimer();
await browser.alarms.clear(AUTO_LOCK_ALARM_NAME);
@@ -150,8 +150,8 @@ export async function handleResetAutoLockTimer(): Promise<void> {
}
// Check if vault is unlocked before setting timer
- const encryptionKey = await storage.getItem(StorageKeys.ENCRYPTION_KEY) as string | null;
- if (!encryptionKey) {
+ const unlockKey = await storage.getItem(StorageKeys.UNLOCK_KEY) as string | null;
+ if (!unlockKey) {
// Vault is already locked, don't start timer
clearShortTimeoutTimer();
await browser.alarms.clear(AUTO_LOCK_ALARM_NAME);
@@ -175,8 +175,8 @@ export async function handlePopupHeartbeat(): Promise<void> {
}
// Check if vault is unlocked
- const encryptionKey = await storage.getItem(StorageKeys.ENCRYPTION_KEY) as string | null;
- if (!encryptionKey) {
+ const unlockKey = await storage.getItem(StorageKeys.UNLOCK_KEY) as string | null;
+ if (!unlockKey) {
// Vault is already locked, don't extend timer
return;
}
@@ -201,8 +201,8 @@ export async function handleSetAutoLockTimeout(timeout: number): Promise<boolean
}
// Check if vault is unlocked before setting new timer
- const encryptionKey = await storage.getItem(StorageKeys.ENCRYPTION_KEY) as string | null;
- if (!encryptionKey) {
+ const unlockKey = await storage.getItem(StorageKeys.UNLOCK_KEY) as string | null;
+ if (!unlockKey) {
// Vault is locked, don't start timer
return true;
}
diff --git a/apps/browser-extension/src/entrypoints/background/VaultMessageHandler.ts b/apps/browser-extension/src/entrypoints/background/VaultMessageHandler.ts
index 1a3ab15f1..15dbdc0dc 100644
--- a/apps/browser-extension/src/entrypoints/background/VaultMessageHandler.ts
+++ b/apps/browser-extension/src/entrypoints/background/VaultMessageHandler.ts
@@ -52,7 +52,7 @@ import { t } from '@/i18n/StandaloneI18n';
import type { ItemUsageAction } from '@aliasvault/client/database';
import type { DraftItem } from '@aliasvault/client/database/ItemRef';
import type { ISqliteDatabase, SqliteValue } from '@aliasvault/client/platform';
-import type { EncryptionKeyDerivationParams } from '@aliasvault/models/metadata';
+import type { UnlockKeyDerivationParams } from '@aliasvault/models/metadata';
/**
* Cache for the SqliteClient to avoid repeated decryption and initialization.
@@ -198,17 +198,18 @@ export async function handleCheckAuthStatus() : Promise<{ isLoggedIn: boolean, i
}
/**
- * Store the encryption key (derived key) in browser storage.
+ * Store the unlock key (the password-derived KEK) 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 handleStoreEncryptionKey(
- encryptionKey: string,
+export async function handleStoreUnlockKey(
+ unlockKey: string,
) : Promise<messageBoolResponse> {
try {
- await storage.setItem(StorageKeys.ENCRYPTION_KEY, encryptionKey);
+ await storage.setItem(StorageKeys.UNLOCK_KEY, unlockKey);
return { success: true };
} catch (error) {
- console.error('Failed to store encryption key:', error);
- // E-602: Storage write failed during encryption key store
+ console.error('Failed to store unlock key:', error);
+ // E-602: Storage write failed during unlock key store
return { success: false, error: formatErrorWithCode(await t('common.errors.unknownErrorTryAgain'), AppErrorCode.STORAGE_WRITE_FAILED) };
}
}
@@ -217,11 +218,11 @@ export async function handleStoreEncryptionKey(
* Store the encryption key derivation parameters in browser storage.
* These are stored in local: storage to enable offline unlock after browser restart.
*/
-export async function handleStoreEncryptionKeyDerivationParams(
- params: EncryptionKeyDerivationParams,
+export async function handleStoreUnlockKeyDerivationParams(
+ params: UnlockKeyDerivationParams,
) : Promise<messageBoolResponse> {
try {
- await storage.setItem(StorageKeys.ENCRYPTION_KEY_DERIVATION_PARAMS, params);
+ await storage.setItem(StorageKeys.UNLOCK_KEY_DERIVATION_PARAMS, params);
return { success: true };
} catch (error) {
console.error('Failed to store encryption key derivation params:', error);
@@ -600,19 +601,20 @@ export async function handleGeneratePassword(
}
/**
- * Get the encryption key for the encrypted vault.
+ * Get the encryption key for the encrypted vault: derived from the session unlock key and the cached key chain,
+ * null while the vault is locked.
*/
export async function handleGetEncryptionKey(
) : Promise<string | null> {
- return await storage.getItem(StorageKeys.ENCRYPTION_KEY) as string | null;
+ return VaultKeyService.getSessionVaultEncryptionKey();
}
/**
* Get the encryption key derivation parameters for password change detection and offline mode.
* These are stored in local: storage to enable offline unlock after browser restart.
*/
-export async function handleGetEncryptionKeyDerivationParams(
-) : Promise<EncryptionKeyDerivationParams | null> {
+export async function handleGetUnlockKeyDerivationParams(
+) : Promise<UnlockKeyDerivationParams | null> {
return MasterPasswordService.getStoredDerivationParams();
}
diff --git a/apps/browser-extension/src/entrypoints/popup/context/DbContext.tsx b/apps/browser-extension/src/entrypoints/popup/context/DbContext.tsx
index 0da3489b0..0f1d88d0c 100644
--- a/apps/browser-extension/src/entrypoints/popup/context/DbContext.tsx
+++ b/apps/browser-extension/src/entrypoints/popup/context/DbContext.tsx
@@ -11,11 +11,11 @@ import { onMessage, sendMessage } from '@/utils/messaging/ExtensionMessaging';
import { getStorageItem } from '@/utils/StorageUtility';
import { syncErrorMessage, toSyncErrorDetail } from '@/utils/SyncError';
-import { markOwnEncryptionKey, vaultStateEvents } from '@/events/VaultStateEvents';
+import { markOwnUnlockKey, vaultStateEvents } from '@/events/VaultStateEvents';
import { t } from '@/i18n/StandaloneI18n';
import type { SyncErrorDetail } from '@aliasvault/client/sync/VaultSync';
-import type { EncryptionKeyDerivationParams } from '@aliasvault/models/metadata';
+import type { UnlockKeyDerivationParams } from '@aliasvault/models/metadata';
import { storage } from '#imports';
@@ -95,8 +95,8 @@ type DbContextType = {
* Returns the SqliteClient if vault was loaded successfully, null otherwise.
*/
loadStoredDatabase: () => Promise<SqliteClient | null>;
- storeEncryptionKey: (derivedKey: string) => Promise<void>;
- storeEncryptionKeyDerivationParams: (params: EncryptionKeyDerivationParams) => Promise<void>;
+ storeUnlockKey: (unlockKey: string) => Promise<void>;
+ storeUnlockKeyDerivationParams: (params: UnlockKeyDerivationParams) => Promise<void>;
clearDatabase: () => void;
getVaultMetadata: () => Promise<VaultMetadata | null>;
/**
@@ -364,22 +364,23 @@ export const DbProvider: React.FC<{ children: React.ReactNode }> = ({ children }
}, [dbInitialized, loadStoredDatabase]);
/**
- * Store encryption key in background worker.
+ * Store the unlock key (the password-derived KEK) 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 storeEncryptionKey = useCallback(async (encryptionKey: string) : Promise<void> => {
+ const storeUnlockKey = useCallback(async (unlockKey: string) : Promise<void> => {
/*
* Mark as our own write BEFORE sending, so the cross-window watcher
* ignores the storage event triggered by this same flow.
*/
- markOwnEncryptionKey(encryptionKey);
- await sendMessage('STORE_ENCRYPTION_KEY', encryptionKey);
+ markOwnUnlockKey(unlockKey);
+ await sendMessage('STORE_UNLOCK_KEY', unlockKey);
}, []);
/**
* Store encryption key derivation params in background worker.
*/
- const storeEncryptionKeyDerivationParams = useCallback(async (params: EncryptionKeyDerivationParams) : Promise<void> => {
- await sendMessage('STORE_ENCRYPTION_KEY_DERIVATION_PARAMS', params);
+ const storeUnlockKeyDerivationParams = useCallback(async (params: UnlockKeyDerivationParams) : Promise<void> => {
+ await sendMessage('STORE_UNLOCK_KEY_DERIVATION_PARAMS', params);
}, []);
/**
@@ -411,8 +412,8 @@ export const DbProvider: React.FC<{ children: React.ReactNode }> = ({ children }
setIsUploading,
shouldSuppressEmailErrors,
loadStoredDatabase,
- storeEncryptionKey,
- storeEncryptionKeyDerivationParams,
+ storeUnlockKey,
+ storeUnlockKeyDerivationParams,
clearDatabase,
getVaultMetadata,
refreshSyncState,
@@ -420,7 +421,7 @@ export const DbProvider: React.FC<{ children: React.ReactNode }> = ({ children }
requiresManifestMigration,
syncError,
clearSyncError,
- }), [sqliteClient, dbInitialized, dbAvailable, isOffline, getIsOffline, hasUnsyncedUserChanges, isSyncing, isUploading, setIsOffline, shouldSuppressEmailErrors, loadStoredDatabase, storeEncryptionKey, storeEncryptionKeyDerivationParams, clearDatabase, getVaultMetadata, refreshSyncState, requiresLegacySqliteBlobMigration, requiresManifestMigration, syncError, clearSyncError]);
+ }), [sqliteClient, dbInitialized, dbAvailable, isOffline, getIsOffline, hasUnsyncedUserChanges, isSyncing, isUploading, setIsOffline, shouldSuppressEmailErrors, loadStoredDatabase, storeUnlockKey, 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.tsx
index f0e73ea61..c186ac62d 100644
--- a/apps/browser-extension/src/entrypoints/popup/pages/auth/Login.tsx
+++ b/apps/browser-extension/src/entrypoints/popup/pages/auth/Login.tsx
@@ -128,19 +128,19 @@ const Login: React.FC = () => {
await app.setAuthTokens(username, token, refreshToken);
/*
- * KEK/VEK: for migrated accounts the derived key is only the KEK; fetch the vault key and decrypt the VEK,
- * which becomes the session encryption key. Legacy accounts keep using the derived key directly.
+ * The derived key is the unlock key (KEK). Fetch the account's key chain, check the key opens it and cache it
+ * as-is; the vault encryption key is derived from the two on demand. Legacy accounts have no chain.
*/
- const encryptionKey = await VaultKeyService.resolveEncryptionKey(passwordHashBase64, webApi);
+ await VaultKeyService.refreshKeyChain(passwordHashBase64, webApi);
- await dbContext.storeEncryptionKeyDerivationParams({
+ await dbContext.storeUnlockKeyDerivationParams({
salt: loginResponse.salt,
encryptionType: loginResponse.encryptionType,
encryptionSettings: loginResponse.encryptionSettings
});
- // Store the session key, then pull and load the vault.
- await dbContext.storeEncryptionKey(encryptionKey);
+ // Store the unlock key as the session key, then pull and load the vault.
+ await dbContext.storeUnlockKey(passwordHashBase64);
await pullAndLoadVault();
// Reset prefill flag so next logout will prefill again
@@ -386,17 +386,12 @@ const Login: React.FC = () => {
// Store auth tokens and username first — the vault fetch below uses the stored access token.
await app.setAuthTokens(result.username, result.token, result.refreshToken);
- /*
- * The mobile device sends the vault encryption key (the encrypted VEK for migrated accounts, or the derived key when
- * the mobile app predates the KEK/VEK model). Refresh the local encrypted VEK cache so offline password unlock
- * keeps working, then upgrade the received key to the encrypted VEK when it turns out to be the KEK.
- */
- await VaultKeyService.cacheEncryptedVekFromServer(webApi);
- const mobileKey = await VaultKeyService.resolveStoredUnlockKey(result.decryptionKey);
+ // The mobile device sends the unlock key: fetch the account's key chain, check the key opens it and cache it.
+ await VaultKeyService.refreshKeyChain(result.decryptionKey, webApi);
- // Store the encryption key and derivation params
- await dbContext.storeEncryptionKey(mobileKey);
- await dbContext.storeEncryptionKeyDerivationParams({
+ // Store the unlock key and derivation params.
+ await dbContext.storeUnlockKey(result.decryptionKey);
+ await dbContext.storeUnlockKeyDerivationParams({
salt: result.salt,
encryptionType: result.encryptionType,
encryptionSettings: result.encryptionSettings,
diff --git a/apps/browser-extension/src/entrypoints/popup/pages/auth/Unlock.tsx b/apps/browser-extension/src/entrypoints/popup/pages/auth/Unlock.tsx
index 9d10c46ab..1867cd9e9 100644
--- a/apps/browser-extension/src/entrypoints/popup/pages/auth/Unlock.tsx
+++ b/apps/browser-extension/src/entrypoints/popup/pages/auth/Unlock.tsx
@@ -33,7 +33,6 @@ import {
IncorrectPinError,
InvalidPinFormatError,
resetFailedAttempts,
- setupPin,
unlockWithPin
} from '@/utils/PinUnlockService';
import type { MobileLoginResult } from '@/utils/types/messaging/MobileLoginResult';
@@ -272,7 +271,7 @@ const Unlock: React.FC = () => {
}
try {
- let passwordHashBase64: string;
+ let unlockKey: string;
if (statusResult.online) {
// Online mode: get encryption params from server for key derivation
@@ -281,21 +280,21 @@ const Unlock: React.FC = () => {
// Derive key from password using user's encryption settings
const credentials = await SrpAuthService.prepareCredentials(password, loginResponse.salt, loginResponse.encryptionSettings);
// Store encryption params for future offline unlock
- await dbContext.storeEncryptionKeyDerivationParams({
+ await dbContext.storeUnlockKeyDerivationParams({
salt: loginResponse.salt,
encryptionType: loginResponse.encryptionType,
encryptionSettings: loginResponse.encryptionSettings,
});
/*
- * KEK/VEK: for migrated accounts the derived key is only the KEK; decrypt the VEK which is the actual
- * vault encryption key. Throws a decrypt-failed (E-203) error on a wrong password. Legacy accounts keep
- * using the derived key directly.
+ * Fetch the account key chain, check the unlock key opens it and cache it as-is. Throws a decrypt-failed
+ * (E-203) error on a wrong password.
*/
- passwordHashBase64 = await VaultKeyService.resolveEncryptionKey(credentials.passwordHashBase64, webApi);
+ unlockKey = credentials.passwordHashBase64;
+ await VaultKeyService.refreshKeyChain(unlockKey, webApi);
} else {
// Offline mode: use stored encryption params to derive key
- const storedParams = await sendMessage('GET_ENCRYPTION_KEY_DERIVATION_PARAMS');
+ const storedParams = await sendMessage('GET_UNLOCK_KEY_DERIVATION_PARAMS');
if (!storedParams) {
// No stored params - can't unlock offline without having logged in before
@@ -308,17 +307,18 @@ const Unlock: React.FC = () => {
const credentials = await SrpAuthService.prepareCredentials(password, storedParams.salt, storedParams.encryptionSettings);
/*
- * KEK/VEK offline: decrypt the locally cached encrypted VEK with the derived key. Throws a decrypt-failed
- * (E-203) error on a wrong password. Legacy accounts (no cached encrypted VEK) use the derived key directly.
+ * Offline: check the unlock key opens the locally cached account key chain. Throws a decrypt-failed
+ * (E-203) error on a wrong password.
*/
- passwordHashBase64 = await VaultKeyService.resolveEncryptionKeyOffline(credentials.passwordHashBase64);
+ unlockKey = credentials.passwordHashBase64;
+ await VaultKeyService.verifyUnlockKey(unlockKey);
// Set offline mode
await dbContext.setIsOffline(true);
}
- // Store the encryption key in session storage.
- await dbContext.storeEncryptionKey(passwordHashBase64);
+ // Store the unlock key in session storage.
+ await dbContext.storeUnlockKey(unlockKey);
/*
* Load the stored vault from background (decrypts using stored encryption key).
@@ -422,15 +422,8 @@ const Unlock: React.FC = () => {
showLoading();
try {
- // Unlock with PIN - this derives the encryption key from the PIN
- let passwordHashBase64 = await unlockWithPin(pinToUse);
-
- /*
- * KEK/VEK: when the PIN was set up before the vault key migration, the PIN-protected key is the old
- * password-derived key (now the KEK). Upgrade to the VEK and re-encrypt the PIN store so future PIN unlocks
- * return the VEK directly.
- */
- passwordHashBase64 = await VaultKeyService.resolveStoredUnlockKey(passwordHashBase64, key => setupPin(pinToUse, key));
+ const unlockKey = await unlockWithPin(pinToUse);
+ await VaultKeyService.verifyUnlockKey(unlockKey);
// Check if we're online or offline (for offline mode flag)
const statusResult = await checkStatus();
@@ -438,8 +431,8 @@ const Unlock: React.FC = () => {
await dbContext.setIsOffline(true);
}
- // Store the encryption key in session storage
- await dbContext.storeEncryptionKey(passwordHashBase64);
+ // Store the unlock key in session storage
+ await dbContext.storeUnlockKey(unlockKey);
/*
* Always unlock from local vault first.
@@ -579,16 +572,13 @@ const Unlock: React.FC = () => {
await authContext.setAuthTokens(result.username, result.token, result.refreshToken);
/*
- * The mobile device sends the vault encryption key (the VEK for migrated accounts, or the derived key when
- * the mobile app predates the KEK/VEK model). Refresh the local encrypted-VEK cache so offline password unlock
- * keeps working, then upgrade the received key to the VEK when it turns out to be the KEK.
+ * The mobile device sends the password-derived key (the KEK).
*/
- await VaultKeyService.cacheEncryptedVekFromServer(webApi);
- const mobileKey = await VaultKeyService.resolveStoredUnlockKey(result.decryptionKey);
+ await VaultKeyService.refreshKeyChain(result.decryptionKey, webApi);
- // Store the encryption key and derivation params
- await dbContext.storeEncryptionKey(mobileKey);
- await dbContext.storeEncryptionKeyDerivationParams({
+ // Store the unlock key and derivation params
+ await dbContext.storeUnlockKey(result.decryptionKey);
+ await dbContext.storeUnlockKeyDerivationParams({
salt: result.salt,
encryptionType: result.encryptionType,
encryptionSettings: result.encryptionSettings,
diff --git a/apps/browser-extension/src/entrypoints/popup/pages/settings/VaultUnlockSettings.tsx b/apps/browser-extension/src/entrypoints/popup/pages/settings/VaultUnlockSettings.tsx
index 3b3b72ded..ffa58dc28 100644
--- a/apps/browser-extension/src/entrypoints/popup/pages/settings/VaultUnlockSettings.tsx
+++ b/apps/browser-extension/src/entrypoints/popup/pages/settings/VaultUnlockSettings.tsx
@@ -1,3 +1,4 @@
+import { VaultKeyService } from '@aliasvault/client/auth/VaultKeyService';
import React, { useEffect, useState, useCallback } from 'react';
import { useTranslation } from 'react-i18next';
@@ -8,7 +9,6 @@ import PageTitle from '@/entrypoints/popup/components/PageTitle';
import { useDb } from '@/entrypoints/popup/context/DbContext';
import { useLoading } from '@/entrypoints/popup/context/LoadingContext';
-import { StorageKeys } from '@/utils/constants/storageKeys';
import { LocalPreferencesService } from '@/utils/LocalPreferencesService';
import {
isPinEnabled,
@@ -19,8 +19,6 @@ import {
InvalidPinFormatError
} from '@/utils/PinUnlockService';
-import { storage } from '#imports';
-
/**
* Vault unlock method settings page component.
*/
@@ -116,19 +114,16 @@ const VaultUnlockSettings: React.FC = () => {
try {
showLoading();
+ const unlockKey = await VaultKeyService.getSessionUnlockKey();
- /* Get the encryption key from session storage */
- const encryptionKeyResponse = await storage.getItem(StorageKeys.ENCRYPTION_KEY) as string | undefined;
- const encryptionKey = encryptionKeyResponse as string;
-
- if (!encryptionKey) {
+ if (!unlockKey) {
setError(t('common.errors.unknownErrorTryAgain'));
hideLoading();
return;
}
- /* Setup PIN with the encryption key */
- await setupPin(newPin, encryptionKey);
+ /* Setup PIN with the unlock key */
+ await setupPin(newPin, unlockKey);
/*
* Mark PIN as the last-used unlock method so the unlock screen defaults to
diff --git a/apps/browser-extension/src/entrypoints/popup/pages/settings/security/ChangePasswordSettings.tsx b/apps/browser-extension/src/entrypoints/popup/pages/settings/security/ChangePasswordSettings.tsx
index 8d0e4bb36..f195ffdb4 100644
--- a/apps/browser-extension/src/entrypoints/popup/pages/settings/security/ChangePasswordSettings.tsx
+++ b/apps/browser-extension/src/entrypoints/popup/pages/settings/security/ChangePasswordSettings.tsx
@@ -13,6 +13,8 @@ import { useLoading } from '@/entrypoints/popup/context/LoadingContext';
import { useWebApi } from '@/entrypoints/popup/context/WebApiContext';
import { useVaultSync } from '@/entrypoints/popup/hooks/useVaultSync';
+import { removeAndDisablePin } from '@/utils/PinUnlockService';
+
type PasswordInputProps = {
id: string;
label: string;
@@ -123,6 +125,10 @@ const ChangePasswordSettings: React.FC = () => {
try {
showLoading();
await MasterPasswordService.changePassword(webApi, currentPassword, newPassword);
+
+ // The PIN protects the key derived from the old password, which no longer opens the account key chain.
+ // TODO: refactor this to automatically update the PIN instead of disabling it?
+ await removeAndDisablePin();
setCurrentPassword('');
setNewPassword('');
setConfirmPassword('');
diff --git a/apps/browser-extension/src/events/VaultStateEvents.ts b/apps/browser-extension/src/events/VaultStateEvents.ts
index 5710a2314..badef4053 100644
--- a/apps/browser-extension/src/events/VaultStateEvents.ts
+++ b/apps/browser-extension/src/events/VaultStateEvents.ts
@@ -6,30 +6,30 @@ type Unsubscribe = () => void;
type Listener = () => void;
/**
- * Last encryption-key value this window wrote, used to ignore our own
+ * Last unlock-key value this window wrote, used to ignore our own
* 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 lastOwnEncryptionKey: string | null = null;
+let lastOwnUnlockKey: string | null = null;
/**
- * Record an encryption-key value that THIS window is about to write. Must be
+ * 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.storeEncryptionKey`.
+ * `DbContext.storeUnlockKey`.
*/
-export function markOwnEncryptionKey(key: string): void {
- lastOwnEncryptionKey = key;
+export function markOwnUnlockKey(key: string): void {
+ lastOwnUnlockKey = key;
}
/*
- * Reset `lastOwnEncryptionKey` whenever the key is cleared in storage (i.e.
+ * Reset `lastOwnUnlockKey` 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.ENCRYPTION_KEY, (newValue) => {
+storage.watch<string | null>(StorageKeys.UNLOCK_KEY, (newValue) => {
if (!newValue) {
- lastOwnEncryptionKey = null;
+ lastOwnUnlockKey = null;
}
});
@@ -39,7 +39,7 @@ storage.watch<string | null>(StorageKeys.ENCRYPTION_KEY, (newValue) => {
export const vaultStateEvents = {
/** Fires when the vault is locked in any window. */
onVaultLocked(listener: Listener): Unsubscribe {
- return storage.watch<string | null>(StorageKeys.ENCRYPTION_KEY, (newValue) => {
+ return storage.watch<string | null>(StorageKeys.UNLOCK_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 `lastOwnEncryptionKey`, which
- * is set synchronously before the write through `markOwnEncryptionKey`.
+ * active window's own write is filtered via `lastOwnUnlockKey`, which
+ * is set synchronously before the write through `markOwnUnlockKey`.
*
* 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.ENCRYPTION_KEY),
+ storage.getItem<string | null>(StorageKeys.UNLOCK_KEY),
storage.getItem<string | null>(StorageKeys.ENCRYPTED_VAULT),
]);
- if (key && vault && key !== lastOwnEncryptionKey) {
+ if (key && vault && key !== lastOwnUnlockKey) {
listener();
}
};
- const unwatchKey = storage.watch<string | null>(StorageKeys.ENCRYPTION_KEY, (newValue) => {
- if (newValue && newValue !== lastOwnEncryptionKey) {
+ const unwatchKey = storage.watch<string | null>(StorageKeys.UNLOCK_KEY, (newValue) => {
+ if (newValue && newValue !== lastOwnUnlockKey) {
void fireIfUnlocked();
}
});
diff --git a/apps/browser-extension/src/utils/PinUnlockService.ts b/apps/browser-extension/src/utils/PinUnlockService.ts
index a60bf93b9..cc7acef84 100644
--- a/apps/browser-extension/src/utils/PinUnlockService.ts
+++ b/apps/browser-extension/src/utils/PinUnlockService.ts
@@ -147,12 +147,12 @@ export async function isPinLocked(): Promise<boolean> {
/**
* Setup PIN unlock
- * Encrypts the vault encryption key with the PIN and stores it
+ * Encrypts the unlock key with the PIN and stores it
*
* @param pin - The PIN to set (6-8 digits)
- * @param vaultEncryptionKey - The base64-encoded vault encryption key to protect
+ * @param unlockKey - The base64-encoded unlock key to protect
*/
-export async function setupPin(pin: string, vaultEncryptionKey: string): Promise<void> {
+export async function setupPin(pin: string, unlockKey: string): Promise<void> {
if (!isValidPin(pin)) {
throw new InvalidPinFormatError();
}
@@ -166,12 +166,12 @@ export async function setupPin(pin: string, vaultEncryptionKey: string): Promise
const combinedSalt = await assembleSaltWithPepper(salt);
const pinKey = await derivePinKey(pin, combinedSalt);
- // Encrypt the vault encryption key
+ // Encrypt the unlock key
const iv = crypto.getRandomValues(new Uint8Array(12));
const encryptedKey = await crypto.subtle.encrypt(
{ name: 'AES-GCM', iv },
pinKey,
- new TextEncoder().encode(vaultEncryptionKey)
+ new TextEncoder().encode(unlockKey)
);
// Combine IV + encrypted data
@@ -202,10 +202,10 @@ export async function setupPin(pin: string, vaultEncryptionKey: string): Promise
/**
* Unlock with PIN
- * Returns the decrypted vault encryption key
+ * Returns the decrypted unlock key (the password-derived KEK)
*
* @param pin - The PIN to use for unlocking
- * @returns The decrypted vault encryption key (base64)
+ * @returns The decrypted unlock key (base64), which opens the account key chain
*/
export async function unlockWithPin(pin: string): Promise<string> {
if (!isValidPin(pin)) {
diff --git a/apps/browser-extension/src/utils/constants/legacyStorageKeys.ts b/apps/browser-extension/src/utils/constants/legacyStorageKeys.ts
index 3212a5ddf..d2264df66 100644
--- a/apps/browser-extension/src/utils/constants/legacyStorageKeys.ts
+++ b/apps/browser-extension/src/utils/constants/legacyStorageKeys.ts
@@ -15,7 +15,7 @@ export const LegacyStorageKeys = {
SESSION_PUBLIC_EMAIL_DOMAINS: 'session:publicEmailDomains',
SESSION_PRIVATE_EMAIL_DOMAINS: 'session:privateEmailDomains',
SESSION_HIDDEN_PRIVATE_EMAIL_DOMAINS: 'session:hiddenPrivateEmailDomains',
- SESSION_ENCRYPTION_KEY_DERIVATION_PARAMS: 'session:encryptionKeyDerivationParams',
+ SESSION_UNLOCK_KEY_DERIVATION_PARAMS: 'session:encryptionKeyDerivationParams',
/** Pre-v0.31 single server revision, superseded by the per-manifest `StorageKeys.SERVER_MANIFEST_REVISIONS`. */
SERVER_REVISION: 'local:serverRevision',
diff --git a/apps/browser-extension/src/utils/legacy/LegacyStorageKeyFallbacks.ts b/apps/browser-extension/src/utils/legacy/LegacyStorageKeyFallbacks.ts
index aa36cbe14..bc649f6b6 100644
--- a/apps/browser-extension/src/utils/legacy/LegacyStorageKeyFallbacks.ts
+++ b/apps/browser-extension/src/utils/legacy/LegacyStorageKeyFallbacks.ts
@@ -20,7 +20,7 @@ const MIGRATED_STORAGE_KEYS: Record<string, StorageKey> = {
[StorageKeys.PUBLIC_EMAIL_DOMAINS]: LegacyStorageKeys.SESSION_PUBLIC_EMAIL_DOMAINS,
[StorageKeys.PRIVATE_EMAIL_DOMAINS]: LegacyStorageKeys.SESSION_PRIVATE_EMAIL_DOMAINS,
[StorageKeys.HIDDEN_PRIVATE_EMAIL_DOMAINS]: LegacyStorageKeys.SESSION_HIDDEN_PRIVATE_EMAIL_DOMAINS,
- [StorageKeys.ENCRYPTION_KEY_DERIVATION_PARAMS]: LegacyStorageKeys.SESSION_ENCRYPTION_KEY_DERIVATION_PARAMS,
+ [StorageKeys.UNLOCK_KEY_DERIVATION_PARAMS]: LegacyStorageKeys.SESSION_UNLOCK_KEY_DERIVATION_PARAMS,
};
/**
diff --git a/apps/browser-extension/src/utils/messaging/ExtensionMessaging.ts b/apps/browser-extension/src/utils/messaging/ExtensionMessaging.ts
index 2a2ec58c5..a189d533e 100644
--- a/apps/browser-extension/src/utils/messaging/ExtensionMessaging.ts
+++ b/apps/browser-extension/src/utils/messaging/ExtensionMessaging.ts
@@ -37,7 +37,7 @@ import type { ItemUsageAction } from '@aliasvault/client/database';
import type { VaultMigrationKind } from '@aliasvault/client/sync/VaultManifestMigration';
import type { VaultMutationScope } from '@aliasvault/client/sync/VaultMutationScope';
import type { FullVaultSyncResult, VaultManifestMigrationResult } from '@aliasvault/client/sync/VaultSync';
-import type { EncryptionKeyDerivationParams } from '@aliasvault/models/metadata';
+import type { UnlockKeyDerivationParams } from '@aliasvault/models/metadata';
import type { PasswordSettings } from '@aliasvault/models/vault';
import type { LoginResponse } from '@aliasvault/models/webapi';
@@ -74,7 +74,7 @@ export interface IExtensionMessageProtocol {
GET_DEFAULT_IDENTITY_SETTINGS(): IdentitySettingsResponse;
GET_ENCRYPTED_VAULT(): string | null;
GET_ENCRYPTION_KEY(): string | null;
- GET_ENCRYPTION_KEY_DERIVATION_PARAMS(): EncryptionKeyDerivationParams | null;
+ GET_UNLOCK_KEY_DERIVATION_PARAMS(): UnlockKeyDerivationParams | null;
GET_FILTERED_ITEMS(data: { currentUrl: string; pageTitle: string; matchingMode?: string; includeRecentlySelected?: boolean }): ItemsResponse;
GET_ITEMS_WITH_TOTP(data: { currentUrl: string; pageTitle: string; matchingMode?: string }): ItemsResponse;
GET_LAST_AUTOFILLED(data: { domain?: string; username?: string }): { success: boolean; credential: LastAutofilledCredential | null };
@@ -116,8 +116,8 @@ export interface IExtensionMessageProtocol {
SET_LOGIN_SAVE_ENABLED(data: boolean): BoolResponse;
SET_RECENTLY_SELECTED(data: { itemId: string; domain: string }): { success: boolean };
STORE_ENCRYPTED_VAULT(data: { vaultBlob: string; markDirty?: boolean; expectedMutationSeq?: number; scope?: VaultMutationScope }): { success: boolean; mutationSequence: number };
- STORE_ENCRYPTION_KEY(data: string): BoolResponse;
- STORE_ENCRYPTION_KEY_DERIVATION_PARAMS(data: EncryptionKeyDerivationParams): BoolResponse;
+ STORE_UNLOCK_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 };
STORE_TWO_FACTOR_STATE(data: { username: string; loginResponse: LoginResponse; passwordHashString: string; passwordHashBase64: string; rememberMe: boolean }): void;
diff --git a/apps/browser-extension/src/utils/types/messaging/MobileLoginResult.ts b/apps/browser-extension/src/utils/types/messaging/MobileLoginResult.ts
index 906f1d713..92a00118f 100644
--- a/apps/browser-extension/src/utils/types/messaging/MobileLoginResult.ts
+++ b/apps/browser-extension/src/utils/types/messaging/MobileLoginResult.ts
@@ -18,7 +18,7 @@ export type MobileLoginResult = {
refreshToken: string;
/**
- * The vault decryption key (base64 encoded).
+ * The unlock key the mobile app sent.
*/
decryptionKey: string;
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.kt
index 85ac87b1e..edc114a27 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 encryption key.
+ * @param data The intent data containing the unlock 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 success
net.aliasvault.app.nativevaultmanager.NativeVaultManager.pendingAuthContext = null
- val encryptionKeyBase64 = data?.getStringExtra(
- net.aliasvault.app.pinunlock.PinUnlockActivity.EXTRA_ENCRYPTION_KEY,
+ val unlockKeyBase64 = data?.getStringExtra(
+ net.aliasvault.app.pinunlock.PinUnlockActivity.EXTRA_UNLOCK_KEY,
)
- if (encryptionKeyBase64 == null) {
- promise.reject("UNLOCK_ERROR", "Failed to get encryption key from PIN unlock", null)
+ if (unlockKeyBase64 == null) {
+ promise.reject("UNLOCK_ERROR", "Failed to get unlock key from PIN unlock", null)
return
}
@@ -161,12 +161,12 @@ class MainActivity : ReactActivity() {
CoroutineScope(Dispatchers.IO).launch {
try {
/*
- * Use storeEncryptionKeyInMemory instead of storeEncryptionKey.
- * storeEncryptionKey would trigger biometric prompt if biometrics is enabled
+ * Use storeUnlockKeyInMemory instead of storeUnlockKey.
+ * storeUnlockKey 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.storeEncryptionKeyInMemory(encryptionKeyBase64)
+ vaultStore.storeUnlockKeyInMemory(unlockKeyBase64)
vaultStore.unlockVault()
promise.resolve(true)
} catch (e: Exception) {
@@ -238,7 +238,7 @@ class MainActivity : ReactActivity() {
/**
* Handle password unlock result.
* @param resultCode The result code from the password unlock activity.
- * @param data The intent data containing the encryption key.
+ * @param data The intent data containing the unlock key.
*/
private fun handlePasswordUnlockResult(resultCode: Int, data: Intent?) {
// Check both promise types - one for showPasswordUnlock() and one for authenticateUser()
@@ -251,11 +251,11 @@ class MainActivity : ReactActivity() {
when (resultCode) {
net.aliasvault.app.passwordunlock.PasswordUnlockActivity.RESULT_SUCCESS -> {
- val encryptionKeyBase64 = data?.getStringExtra(
- net.aliasvault.app.passwordunlock.PasswordUnlockActivity.EXTRA_ENCRYPTION_KEY,
+ val unlockKeyBase64 = data?.getStringExtra(
+ net.aliasvault.app.passwordunlock.PasswordUnlockActivity.EXTRA_UNLOCK_KEY,
)
- if (encryptionKeyBase64 == null) {
+ if (unlockKeyBase64 == null) {
passwordPromise?.resolve(null)
authPromise?.resolve(false)
return
@@ -269,8 +269,8 @@ class MainActivity : ReactActivity() {
// Run on IO thread to avoid blocking main thread
kotlinx.coroutines.CoroutineScope(kotlinx.coroutines.Dispatchers.IO).launch {
try {
- // Store encryption key in memory only
- vaultStore.storeEncryptionKeyInMemory(encryptionKeyBase64)
+ // Store unlock key in memory only
+ vaultStore.storeUnlockKeyInMemory(unlockKeyBase64)
// Unlock the vault with the key now in memory
vaultStore.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.kt
index e8974fef4..a51e3c2d3 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.storeEncryptionKeyInMemory(result)
+ vaultStore.storeUnlockKeyInMemory(result)
vaultStore.unlockVault()
// Notify success
@@ -121,7 +121,7 @@ class UnlockCoordinator(
}
override fun onError(e: Exception) {
- Log.e(TAG, "Failed to retrieve encryption key", e)
+ Log.e(TAG, "Failed to retrieve unlock 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 encryption key and unlock vault
- val encryptionKey = data?.getStringExtra(PinUnlockActivity.EXTRA_ENCRYPTION_KEY)
- if (encryptionKey != null) {
+ // PIN unlock successful - get unlock key and unlock vault
+ val unlockKey = data?.getStringExtra(PinUnlockActivity.EXTRA_UNLOCK_KEY)
+ if (unlockKey != null) {
try {
- vaultStore.storeEncryptionKeyInMemory(encryptionKey)
+ vaultStore.storeUnlockKeyInMemory(unlockKey)
vaultStore.unlockVault()
onUnlocked()
} catch (e: Exception) {
@@ -148,7 +148,7 @@ class UnlockCoordinator(
onError(getUnlockErrorMessage(e))
}
} else {
- Log.e(TAG, "No encryption key returned from PIN unlock")
+ Log.e(TAG, "No unlock key returned from PIN unlock")
onError("Failed to unlock vault")
}
}
@@ -177,10 +177,10 @@ class UnlockCoordinator(
fun handlePasswordUnlockResult(resultCode: Int, data: Intent?) {
when (resultCode) {
PasswordUnlockActivity.RESULT_SUCCESS -> {
- val encryptionKey = data?.getStringExtra(PasswordUnlockActivity.EXTRA_ENCRYPTION_KEY)
- if (encryptionKey != null) {
+ val unlockKey = data?.getStringExtra(PasswordUnlockActivity.EXTRA_UNLOCK_KEY)
+ if (unlockKey != null) {
try {
- vaultStore.storeEncryptionKeyInMemory(encryptionKey)
+ vaultStore.storeUnlockKeyInMemory(unlockKey)
vaultStore.unlockVault()
onUnlocked()
} catch (e: Exception) {
@@ -188,7 +188,7 @@ class UnlockCoordinator(
onError(getUnlockErrorMessage(e))
}
} else {
- Log.e(TAG, "No encryption key returned from password unlock")
+ Log.e(TAG, "No unlock key returned from password unlock")
onError("Failed to unlock vault")
}
}
diff --git a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/nativevaultmanager/NativeVaultManager.kt b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/nativevaultmanager/NativeVaultManager.kt
index 4b3820960..e630164ed 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
@@ -240,35 +240,35 @@ class NativeVaultManager(reactContext: ReactApplicationContext) :
}
/**
- * Store the encryption key in memory only (no keystore persistence).
+ * Open a session in memory with the unlock key, without keystore persistence.
* Use this to test if a password-derived key is valid before persisting.
- * @param base64EncryptionKey The encryption key as a base64 encoded string
+ * @param base64UnlockKey The unlock key as a base64 encoded string
* @param promise The promise to resolve
*/
@ReactMethod
- override fun storeEncryptionKeyInMemory(base64EncryptionKey: String, promise: Promise) {
+ override fun storeUnlockKeyInMemory(base64UnlockKey: String, promise: Promise) {
try {
- vaultStore.storeEncryptionKeyInMemory(base64EncryptionKey)
+ vaultStore.storeUnlockKeyInMemory(base64UnlockKey)
promise.resolve(null)
} catch (e: Exception) {
- Log.e(TAG, "Error storing encryption key in memory", e)
- promise.reject("ERR_STORE_KEY_MEMORY", "Failed to store encryption key in memory: ${e.message}", e)
+ 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)
}
}
/**
- * Store the encryption key in memory AND persist to keystore (may trigger biometric prompt).
- * @param base64EncryptionKey The encryption key as a base64 encoded string
+ * 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
* @param promise The promise to resolve
*/
@ReactMethod
- override fun storeEncryptionKey(base64EncryptionKey: String, promise: Promise) {
+ override fun storeUnlockKey(base64UnlockKey: String, promise: Promise) {
try {
- vaultStore.storeEncryptionKey(base64EncryptionKey)
+ vaultStore.storeUnlockKey(base64UnlockKey)
promise.resolve(null)
} catch (e: Exception) {
- Log.e(TAG, "Error storing encryption key", e)
- promise.reject("ERR_STORE_KEY", "Failed to store encryption key: ${e.message}", e)
+ Log.e(TAG, "Error storing unlock key", e)
+ promise.reject("ERR_STORE_KEY", "Failed to store unlock key: ${e.message}", e)
}
}
@@ -289,9 +289,9 @@ class NativeVaultManager(reactContext: ReactApplicationContext) :
* @param promise The promise to resolve
*/
@ReactMethod
- override fun storeEncryptionKeyDerivationParams(keyDerivationParams: String, promise: Promise) {
+ override fun storeUnlockKeyDerivationParams(keyDerivationParams: String, promise: Promise) {
try {
- vaultStore.storeEncryptionKeyDerivationParams(keyDerivationParams)
+ vaultStore.storeUnlockKeyDerivationParams(keyDerivationParams)
promise.resolve(null)
} catch (e: Exception) {
Log.e(TAG, "Error storing key derivation params", e)
@@ -308,9 +308,9 @@ class NativeVaultManager(reactContext: ReactApplicationContext) :
* @param promise The promise to resolve
*/
@ReactMethod
- override fun getEncryptionKeyDerivationParams(promise: Promise) {
+ override fun getUnlockKeyDerivationParams(promise: Promise) {
try {
- val params = vaultStore.getEncryptionKeyDerivationParams()
+ val params = vaultStore.getUnlockKeyDerivationParams()
promise.resolve(params)
} catch (e: Exception) {
Log.e(TAG, "Error getting key derivation params", e)
@@ -348,7 +348,7 @@ class NativeVaultManager(reactContext: ReactApplicationContext) :
}
/**
- * Resolve and store the vault key right after login from the password-derived key (see VaultStore.resolveVaultKey).
+ * 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.
* @param base64DerivedKey The password-derived key as base64
* @param promise The promise to resolve
@@ -1624,14 +1624,15 @@ class NativeVaultManager(reactContext: ReactApplicationContext) :
/**
* Show native PIN setup UI.
* Launches the native PinUnlockActivity in setup mode.
- * Gets the vault encryption key from memory (vault must be unlocked).
+ * Gets the unlock 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.
*/
@ReactMethod
override fun showPinSetup(promise: Promise) {
- // Get encryption key first
- vaultStore.getEncryptionKey(object : net.aliasvault.app.vaultstore.interfaces.CryptoOperationCallback {
- override fun onSuccess(encryptionKey: String) {
+ // Get the unlock key first
+ vaultStore.getUnlockKey(object : net.aliasvault.app.vaultstore.interfaces.CryptoOperationCallback {
+ override fun onSuccess(unlockKey: String) {
try {
val activity = currentActivity
if (activity == null) {
@@ -1645,7 +1646,7 @@ class NativeVaultManager(reactContext: ReactApplicationContext) :
// Launch PIN setup activity
val 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_ENCRYPTION_KEY, encryptionKey)
+ intent.putExtra(net.aliasvault.app.pinunlock.PinUnlockActivity.EXTRA_SETUP_UNLOCK_KEY, unlockKey)
activity.startActivityForResult(intent, PIN_SETUP_REQUEST_CODE)
} catch (e: Exception) {
@@ -1655,8 +1656,8 @@ class NativeVaultManager(reactContext: ReactApplicationContext) :
}
override fun onError(error: Exception) {
- Log.e(TAG, "Error getting encryption key for PIN setup", error)
- promise.reject("ERR_SETUP_PIN", "Failed to get encryption key: ${error.message}", error)
+ Log.e(TAG, "Error getting unlock key for PIN setup", error)
+ promise.reject("ERR_SETUP_PIN", "Failed to get unlock key: ${error.message}", error)
}
})
}
diff --git a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/passwordunlock/PasswordUnlockActivity.kt b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/passwordunlock/PasswordUnlockActivity.kt
index 4d2197c96..8185e2d92 100644
--- a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/passwordunlock/PasswordUnlockActivity.kt
+++ b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/passwordunlock/PasswordUnlockActivity.kt
@@ -35,7 +35,7 @@ import net.aliasvault.app.vaultstore.storageprovider.AndroidStorageProvider
* This activity presents a password entry UI for vault unlocking.
*
* Result:
- * - RESULT_SUCCESS: Password verified, encryption key returned in EXTRA_ENCRYPTION_KEY
+ * - RESULT_SUCCESS: Password verified, unlock key returned in EXTRA_UNLOCK_KEY
* - RESULT_CANCELLED: User cancelled
*/
class PasswordUnlockActivity : AppCompatActivity() {
@@ -50,8 +50,8 @@ class PasswordUnlockActivity : AppCompatActivity() {
/** Result code for max attempts reached - user has been logged out. */
const val RESULT_MAX_ATTEMPTS_REACHED = Activity.RESULT_FIRST_USER + 1
- /** Intent extra key for the encryption key (returned on success). */
- const val EXTRA_ENCRYPTION_KEY = "encryption_key"
+ /** Intent extra key for the unlock key, the password-derived KEK (returned on success). */
+ const val EXTRA_UNLOCK_KEY = "unlock_key"
/** Intent extra key for custom title (optional). */
const val EXTRA_CUSTOM_TITLE = "custom_title"
@@ -267,15 +267,15 @@ class PasswordUnlockActivity : AppCompatActivity() {
CoroutineScope(Dispatchers.Main).launch {
try {
- val encryptionKey = withContext(Dispatchers.IO) {
+ val unlockKey = withContext(Dispatchers.IO) {
vaultStore.verifyPassword(password)
}
- if (encryptionKey != null) {
- // Success - reset failed attempts counter and return encryption key
+ if (unlockKey != null) {
+ // Success - reset failed attempts counter and return unlock key
resetFailedAttempts()
val resultIntent = Intent().apply {
- putExtra(EXTRA_ENCRYPTION_KEY, encryptionKey)
+ putExtra(EXTRA_UNLOCK_KEY, unlockKey)
}
setResult(RESULT_SUCCESS, resultIntent)
finish()
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.kt
index 73e95f170..c38d0606e 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 encryptionKey The encryption key (returned for unlock mode, null for setup mode).
+ * @property unlockKey The unlock key (returned for unlock mode, null for setup mode).
*/
- data class Success(val encryptionKey: String?) : PinResult()
+ data class Success(val unlockKey: 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.kt
index 8de638b95..396f67dff 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_ENCRYPTION_KEY, encryptionKey)
+ * intent.putExtra(PinUnlockActivity.EXTRA_SETUP_UNLOCK_KEY, unlockKey)
* 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 encryption key (returned in unlock mode). */
- const val EXTRA_ENCRYPTION_KEY = "encryption_key"
+ /** Intent extra key for the unlock key, the password-derived KEK (returned in unlock mode). */
+ const val EXTRA_UNLOCK_KEY = "unlock_key"
/** Intent extra key for the mode (unlock or setup). */
const val EXTRA_MODE = "mode"
- /** Intent extra key for the encryption key to use during setup. */
- const val EXTRA_SETUP_ENCRYPTION_KEY = "setup_encryption_key"
+ /** Intent extra key for the unlock key (the password-derived KEK) the PIN protects during setup. */
+ const val EXTRA_SETUP_UNLOCK_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() {
// State
private var configuration: PinConfiguration? = null
- private var setupEncryptionKey: String? = null
+ private var setupUnlockKey: String? = null
private var currentPin: String = ""
private var isProcessing: Boolean = false
@@ -118,12 +118,12 @@ class PinUnlockActivity : AppCompatActivity() {
)
viewModel = PinViewModel(this, vaultStore)
- // Get mode and encryption key from intent
+ // Get mode and unlock key from intent
val mode = when (intent.getStringExtra(EXTRA_MODE)) {
MODE_SETUP -> PinMode.SETUP
else -> PinMode.UNLOCK
}
- setupEncryptionKey = intent.getStringExtra(EXTRA_SETUP_ENCRYPTION_KEY)
+ setupUnlockKey = intent.getStringExtra(EXTRA_SETUP_UNLOCK_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, setupEncryptionKey)
+ val result = viewModel.processPin(currentPin, config, setupUnlockKey)
// Handle result
handlePinResult(result)
@@ -451,8 +451,8 @@ class PinUnlockActivity : AppCompatActivity() {
// Success - return result
val resultIntent = Intent()
- result.encryptionKey?.let {
- resultIntent.putExtra(EXTRA_ENCRYPTION_KEY, it)
+ result.unlockKey?.let {
+ resultIntent.putExtra(EXTRA_UNLOCK_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.kt
index f35b8a535..1a1de9444 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,
- setupEncryptionKey: String? = null,
+ setupUnlockKey: String? = null,
): PinResult = withContext(Dispatchers.IO) {
return@withContext when (configuration.mode) {
PinMode.UNLOCK -> processUnlock(pin)
- PinMode.SETUP -> processSetup(pin, configuration, setupEncryptionKey)
+ PinMode.SETUP -> processSetup(pin, configuration, setupUnlockKey)
}
}
@@ -67,8 +67,8 @@ class PinViewModel(
*/
private fun processUnlock(pin: String): PinResult {
return try {
- val encryptionKey = vaultStore.unlockWithPin(pin)
- PinResult.Success(encryptionKey)
+ val unlockKey = vaultStore.unlockWithPin(pin)
+ PinResult.Success(unlockKey)
} catch (e: PinUnlockException) {
when (e) {
is PinUnlockException.Locked -> {
@@ -95,7 +95,7 @@ class PinViewModel(
private fun processSetup(
pin: String,
configuration: PinConfiguration,
- setupEncryptionKey: String?,
+ setupUnlockKey: String?,
): PinResult {
return when (configuration.setupStep) {
PinSetupStep.ENTER_NEW -> {
@@ -131,13 +131,13 @@ class PinViewModel(
// Setup the PIN
try {
- if (setupEncryptionKey == null) {
+ if (setupUnlockKey == null) {
return PinResult.Error(
- "Encryption key required for PIN setup",
+ "Unlock key required for PIN setup",
shouldClear = false,
)
}
- vaultStore.setupPin(pin, setupEncryptionKey)
+ vaultStore.setupPin(pin, setupUnlockKey)
PinResult.Success(null)
} catch (e: Exception) {
PinResult.Error(
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.kt
index 2532d16e3..ebe657403 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
@@ -72,14 +72,35 @@ class VaultCrypto(
}
/**
- * The encryption key.
+ * The unlock 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.
*/
- internal var encryptionKey: ByteArray? = null
+ internal var unlockKey: ByteArray? = null
/**
- * The account private key (JWK) of the unlocked session, when the sync engine opened it; memory only.
+ * The encryption key for the vault, derived from the unlock key. Null while the vault is locked.
*/
- internal var accountPrivateKey: String? = null
+ internal val encryptionKey: ByteArray?
+ get() = sessionKeys()?.vaultEncryptionKey
+
+ /**
+ * The account private key (JWK) of the unlocked session, derived from the unlock key.
+ */
+ internal val accountPrivateKey: String?
+ get() = sessionKeys()?.accountPrivateKey
+
+ /**
+ * What the unlock key opens in the cached account key chain.
+ */
+ @Suppress("SwallowedException")
+ private fun sessionKeys(): SessionKeys? {
+ val key = unlockKey ?: return null
+ return try {
+ openAccountKeyChain(key)
+ } catch (e: Exception) {
+ null
+ }
+ }
// region Key Derivation
@@ -102,15 +123,16 @@ class VaultCrypto(
// region Encryption Key Management
/**
- * Store the encryption key in memory and optionally persist to keystore if biometrics are enabled.
+ * Open a session with the unlock key and optionally persist that key to keystore if
+ * biometrics are enabled.
*
* During login, if biometrics are enabled, this will attempt to persist the key to keystore.
* However, if Activity context is not available (common during login before UI is fully ready),
* the key will only be stored in memory. It will be persisted to keystore on next unlock
* when Activity context is available.
*/
- fun storeEncryptionKey(base64EncryptionKey: String, authMethods: String) {
- this.encryptionKey = Base64.decode(base64EncryptionKey, Base64.NO_WRAP)
+ fun storeUnlockKey(base64UnlockKey: String, authMethods: String) {
+ openSession(Base64.decode(base64UnlockKey, Base64.NO_WRAP))
if (authMethods.contains(BIOMETRICS_AUTH_METHOD)) {
try {
@@ -118,7 +140,7 @@ class VaultCrypto(
var error: Exception? = null
keystoreProvider.storeKey(
- key = base64EncryptionKey,
+ key = base64UnlockKey,
object : KeystoreOperationCallback {
override fun onSuccess(result: String) {
Log.d(TAG, "Encryption key stored successfully with biometric protection")
@@ -148,38 +170,37 @@ class VaultCrypto(
}
/**
- * Store the encryption key in memory only.
+ * Open a session in memory only with the unlock key.
*/
- fun storeEncryptionKeyInMemory(base64EncryptionKey: String) {
- this.encryptionKey = Base64.decode(base64EncryptionKey, Base64.NO_WRAP)
+ fun storeUnlockKeyInMemory(base64UnlockKey: String) {
+ openSession(Base64.decode(base64UnlockKey, Base64.NO_WRAP))
}
/**
- * Clear the encryption key from memory.
- * This forces getEncryptionKey() to fetch from keystore on next biometric access.
+ * Clear the unlock key from memory.
+ * This forces getEncryptionKey() to fetch the unlock key from keystore on next biometric access.
*/
fun clearEncryptionKeyFromMemory() {
- this.encryptionKey = null
- this.accountPrivateKey = null
+ clearKey()
}
/**
* Store the encryption key derivation parameters.
*/
- fun storeEncryptionKeyDerivationParams(keyDerivationParams: String) {
+ fun storeUnlockKeyDerivationParams(keyDerivationParams: String) {
storageProvider.setKeyDerivationParams(keyDerivationParams)
}
/**
* Get the encryption key derivation parameters.
*/
- fun getEncryptionKeyDerivationParams(): String {
+ fun getUnlockKeyDerivationParams(): String {
return storageProvider.getKeyDerivationParams()
}
/**
* Store the account-key chain the native password unlock unwraps: JSON with the Account Key wrapped by the
- * password-derived KEK ("encryptedAccountKey") and the VEK wrapped by the Account Key ("encryptedVek").
+ * unlock key ("encryptedAccountKey") and the VEK wrapped by the Account Key ("encryptedVek").
* Null means a legacy account whose KEK encrypts the vault directly.
*/
fun storeAccountKeyChain(chainJson: String?) {
@@ -193,31 +214,51 @@ class VaultCrypto(
return storageProvider.getAccountKeyChain()
}
+ /*
+ * The unlock key is the one secret a session holds; keystore and PIN only protect
+ * that same key. It opens the cached account key chain as the server returned it: KEK > Account Key > vault key
+ * and account private key, which are derived on demand and never stored. A legacy account has no chain and its
+ * KEK is the vault key.
+ */
+
/**
- * Turn a password-derived key (KEK) into the vault encryption key: unwrap KEK > Account Key > VEK when the
- * account has a key chain, otherwise the derived key is the vault key itself (legacy account).
+ * 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
*/
- fun resolveVaultEncryptionKey(derivedKey: ByteArray): ByteArray {
- val chainJson = getAccountKeyChain() ?: return derivedKey
+ class SessionKeys(val vaultEncryptionKey: ByteArray, val accountPrivateKey: String?)
+
+ /**
+ * Open the cached account key chain with the KEK. Without a chain (legacy account) the KEK is the vault key.
+ */
+ @Suppress("SwallowedException")
+ fun openAccountKeyChain(derivedKey: ByteArray): SessionKeys {
+ val chainJson = getAccountKeyChain() ?: return SessionKeys(derivedKey, null)
val chain = JSONObject(chainJson)
- val encryptedAccountKey = chain.optString("encryptedAccountKey").takeIf { it.isNotEmpty() } ?: return derivedKey
+ val encryptedAccountKey = chain.optString("encryptedAccountKey").takeIf { it.isNotEmpty() } ?: return SessionKeys(derivedKey, null)
val encryptedVek = chain.optString("encryptedVek").takeIf { it.isNotEmpty() } ?: error("Account key chain is missing the encrypted VEK")
val accountKey = decrypt(Base64.decode(encryptedAccountKey, Base64.NO_WRAP), derivedKey)
- return decrypt(Base64.decode(encryptedVek, Base64.NO_WRAP), accountKey)
+ val vaultEncryptionKey = decrypt(Base64.decode(encryptedVek, Base64.NO_WRAP), accountKey)
+
+ // A private key that does not open must not fail the unlock; grants stay closed until the next login.
+ val accountPrivateKey = chain.optString("encryptedAccountPrivateKey").takeIf { it.isNotEmpty() }?.let {
+ try {
+ String(decrypt(Base64.decode(it, Base64.NO_WRAP), accountKey), Charsets.UTF_8)
+ } catch (e: Exception) {
+ null
+ }
+ }
+ return SessionKeys(vaultEncryptionKey, accountPrivateKey)
}
/**
- * The vault key an unlock method (PIN) stored, as base64. A snapshot taken before the account moved onto the key
- * hierarchy still holds the password-derived key; when that opens the stored chain, the VEK behind it is returned.
+ * Open a session with the unlock key, after checking that it opens the cached account key chain.
*/
- @Suppress("SwallowedException")
- fun resolveStoredUnlockKey(base64Key: String): String {
- return try {
- Base64.encodeToString(resolveVaultEncryptionKey(Base64.decode(base64Key, Base64.NO_WRAP)), Base64.NO_WRAP)
- } catch (e: Exception) {
- base64Key
- }
+ fun openSession(unlockKey: ByteArray) {
+ openAccountKeyChain(unlockKey)
+ this.unlockKey = unlockKey
}
/**
@@ -228,10 +269,25 @@ class VaultCrypto(
}
/**
- * Get the encryption key.
+ * Get the encryption key, the key that encrypts and decrypts the vault.
*/
fun getEncryptionKey(callback: CryptoOperationCallback, authMethods: String) {
- encryptionKey?.let {
+ withSession(callback, authMethods) { encryptionKey }
+ }
+
+ /**
+ * Get the unlock key, the keystore and PIN protect.
+ */
+ fun getUnlockKey(callback: CryptoOperationCallback, authMethods: String) {
+ withSession(callback, authMethods) { unlockKey }
+ }
+
+ /**
+ * Hand one of the session keys to the callback, opening the session from the keystore behind a biometric prompt
+ * when none is open.
+ */
+ private fun withSession(callback: CryptoOperationCallback, authMethods: String, key: () -> ByteArray?) {
+ key()?.let {
callback.onSuccess(Base64.encodeToString(it, Base64.NO_WRAP))
return
}
@@ -241,11 +297,11 @@ class VaultCrypto(
object : KeystoreOperationCallback {
override fun onSuccess(result: String) {
try {
- encryptionKey = Base64.decode(result, Base64.NO_WRAP)
- callback.onSuccess(result)
+ openSession(Base64.decode(result, Base64.NO_WRAP))
+ callback.onSuccess(Base64.encodeToString(key(), Base64.NO_WRAP))
} catch (e: Exception) {
- Log.e(TAG, "Error decoding retrieved key", e)
- callback.onError(e)
+ Log.e(TAG, "The unlock key from the keystore does not open the account key chain", e)
+ callback.onError(AppError.VaultDecryptFailed(cause = e))
}
}
@@ -265,8 +321,7 @@ class VaultCrypto(
* Clear the encryption key from memory.
*/
fun clearKey() {
- encryptionKey = null
- accountPrivateKey = null
+ unlockKey = null
}
// endregion
@@ -367,14 +422,15 @@ class VaultCrypto(
// region Mobile Login
/**
- * Encrypts the vault's encryption key using an RSA public key for mobile login.
+ * Encrypts the unlock 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 encryptDecryptionKeyForMobileLogin(publicKeyJWK: String, authMethods: String): String {
var result: String? = null
var error: Exception? = null
val latch = java.util.concurrent.CountDownLatch(1)
- getEncryptionKey(
+ getUnlockKey(
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.kt
index c14accf2d..8434cc29e 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
@@ -68,7 +68,7 @@ class VaultDatabase(
* Check if the vault is unlocked.
*/
fun isVaultUnlocked(): Boolean {
- return crypto.encryptionKey != null
+ return crypto.unlockKey != 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.kt
index 24ffebbea..8844db72d 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 vault encryption key
+ * This component manages PIN-based unlocking by encrypting the unlock key
* with a key derived from the user's PIN using Argon2id.
*
* Security features:
@@ -130,17 +130,17 @@ class VaultPin(
/**
* Setup PIN unlock.
- * Encrypts the vault encryption key with the PIN and stores it securely.
+ * Encrypts the unlock key with the PIN and stores it securely.
*
* @param pin The PIN to set (4+ digits)
- * @param vaultEncryptionKeyBase64 The base64-encoded vault encryption key to protect
+ * @param unlockKeyBase64 The base64-encoded unlock key to protect
* @throws IllegalArgumentException if PIN format is invalid
* @throws Exception if encryption or storage fails
*/
@Throws(Exception::class)
- fun setupPin(pin: String, vaultEncryptionKeyBase64: String) {
- // Decode the vault encryption key
- val vaultEncryptionKey = Base64.decode(vaultEncryptionKeyBase64, Base64.NO_WRAP)
+ fun setupPin(pin: String, unlockKeyBase64: String) {
+ // Decode the unlock key
+ val unlockKey = Base64.decode(unlockKeyBase64, Base64.NO_WRAP)
// Generate random salt
val salt = ByteArray(16)
@@ -149,7 +149,7 @@ class VaultPin(
// Derive key from PIN + salt using Argon2id
val pinKey = derivePinKey(pin, salt)
- // Encrypt the vault encryption key using AES-GCM
+ // Encrypt the unlock key using AES-GCM
val cipher = Cipher.getInstance("AES/GCM/NoPadding")
val secretKey = SecretKeySpec(pinKey, "AES")
@@ -158,7 +158,7 @@ class VaultPin(
SecureRandom().nextBytes(iv)
cipher.init(Cipher.ENCRYPT_MODE, secretKey, GCMParameterSpec(GCM_TAG_LENGTH, iv))
- val encryptedKey = cipher.doFinal(vaultEncryptionKey)
+ val encryptedKey = cipher.doFinal(unlockKey)
// Combine IV + encrypted data
val combined = ByteArray(iv.size + encryptedKey.size)
@@ -185,10 +185,10 @@ class VaultPin(
/**
* Unlock with PIN.
- * Returns the decrypted vault encryption key.
+ * Returns the decrypted unlock key.
*
* @param pin The PIN to use for unlocking
- * @return The decrypted vault encryption key (base64)
+ * @return The decrypted unlock key (base64)
* @throws PinUnlockException with specific error type and metadata
*/
@Throws(PinUnlockException::class)
@@ -205,7 +205,7 @@ class VaultPin(
// Derive key from PIN + salt
val pinKey = derivePinKey(pin, salt)
- // Decrypt the vault encryption key
+ // Decrypt the unlock key
val cipher = Cipher.getInstance("AES/GCM/NoPadding")
val secretKey = SecretKeySpec(pinKey, "AES")
cipher.init(Cipher.DECRYPT_MODE, secretKey, GCMParameterSpec(GCM_TAG_LENGTH, iv))
@@ -214,7 +214,7 @@ class VaultPin(
// Reset failed attempts on success
storePinFailedAttemptsInKeystore(0)
- // Return the decrypted vault encryption key as base64
+ // Return the decrypted unlock key as base64
return Base64.encodeToString(decryptedKey, Base64.NO_WRAP)
} catch (e: Exception) {
// Increment failed attempts
diff --git a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultStore.kt b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultStore.kt
index 088279e55..bab877808 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
@@ -144,11 +144,8 @@ class VaultStore(
/**
* Internal accessor for encryption key.
*/
- internal var encryptionKey: ByteArray?
+ internal val encryptionKey: ByteArray?
get() = crypto.encryptionKey
- set(value) {
- crypto.encryptionKey = value
- }
/**
* Internal accessor for VaultAuth.
@@ -167,17 +164,18 @@ class VaultStore(
// region Crypto Methods
/**
- * Store the encryption key.
+ * Open a session with the unlock key and persist that key to keystore if biometrics
+ * are enabled.
*/
- fun storeEncryptionKey(base64EncryptionKey: String) {
- crypto.storeEncryptionKey(base64EncryptionKey, auth.getAuthMethods())
+ fun storeUnlockKey(base64UnlockKey: String) {
+ crypto.storeUnlockKey(base64UnlockKey, auth.getAuthMethods())
}
/**
- * Store the encryption key in memory only.
+ * Open a session in memory only with the unlock key.
*/
- fun storeEncryptionKeyInMemory(base64EncryptionKey: String) {
- crypto.storeEncryptionKeyInMemory(base64EncryptionKey)
+ fun storeUnlockKeyInMemory(base64UnlockKey: String) {
+ crypto.storeUnlockKeyInMemory(base64UnlockKey)
}
/**
@@ -196,6 +194,13 @@ class VaultStore(
crypto.getEncryptionKey(callback, auth.getAuthMethods())
}
+ /**
+ * Get the unlock key, the keystore and PIN protect.
+ */
+ fun getUnlockKey(callback: CryptoOperationCallback) {
+ crypto.getUnlockKey(callback, auth.getAuthMethods())
+ }
+
/**
* Check if biometric authentication is enabled and available.
*/
@@ -206,15 +211,15 @@ class VaultStore(
/**
* Store the encryption key derivation parameters.
*/
- fun storeEncryptionKeyDerivationParams(keyDerivationParams: String) {
- crypto.storeEncryptionKeyDerivationParams(keyDerivationParams)
+ fun storeUnlockKeyDerivationParams(keyDerivationParams: String) {
+ crypto.storeUnlockKeyDerivationParams(keyDerivationParams)
}
/**
* Get the encryption key derivation parameters.
*/
- fun getEncryptionKeyDerivationParams(): String {
- return crypto.getEncryptionKeyDerivationParams()
+ fun getUnlockKeyDerivationParams(): String {
+ return crypto.getUnlockKeyDerivationParams()
}
/**
@@ -232,13 +237,10 @@ class VaultStore(
}
/**
- * The account private key (JWK) of the unlocked session, or null until a sync opened it; memory only.
+ * The account private key (JWK) of the unlocked session, derived from the unlock key; null for an account without a keypair.
*/
- internal var accountPrivateKey: String?
+ internal val accountPrivateKey: String?
get() = crypto.accountPrivateKey
- set(value) {
- crypto.accountPrivateKey = value
- }
/**
* Derive a key from a password using Argon2Id.
@@ -253,24 +255,24 @@ class VaultStore(
}
/**
- * Encrypts the vault's encryption key using an RSA public key for mobile login.
+ * Encrypts the unlock key using an RSA public key for mobile login.
*/
fun encryptDecryptionKeyForMobileLogin(publicKeyJWK: String): String {
return crypto.encryptDecryptionKeyForMobileLogin(publicKeyJWK, auth.getAuthMethods())
}
/**
- * Verify the password and return the vault encryption key if correct: the VEK unwrapped through the
- * account-key chain, or the derived key itself for a legacy account. Returns null if the password is incorrect.
+ * Verify the password and return the unlock key if correct. Returns null if the
+ * password is incorrect.
*
* @param password The password to verify
- * @return The base64-encoded vault encryption key if password is correct, null otherwise
+ * @return The base64-encoded unlock key if password is correct, null otherwise
*/
@Suppress("SwallowedException")
fun verifyPassword(password: String): String? {
return try {
// Get encryption key derivation parameters
- val params = crypto.getEncryptionKeyDerivationParams()
+ val params = crypto.getUnlockKeyDerivationParams()
val paramsJson = org.json.JSONObject(params)
val salt = paramsJson.getString("salt")
val encryptionType = paramsJson.getString("encryptionType")
@@ -278,17 +280,17 @@ class VaultStore(
// Derive the KEK from the password and unwrap the chain; a wrong password fails the unwrap.
val derivedKey = crypto.deriveKeyFromPassword(password, salt, encryptionType, encryptionSettings)
- val vaultKey = crypto.resolveVaultEncryptionKey(derivedKey)
+ val vaultEncryptionKey = crypto.openAccountKeyChain(derivedKey).vaultEncryptionKey
// Try to decrypt the vault to verify the password is correct
val encryptedDb = database.getEncryptedDatabase()
val encryptedDbBytes = android.util.Base64.decode(encryptedDb, android.util.Base64.NO_WRAP)
// Attempt decryption to verify password is correct
- VaultCrypto.decrypt(encryptedDbBytes, vaultKey)
+ VaultCrypto.decrypt(encryptedDbBytes, vaultEncryptionKey)
- // If decryption succeeded, return the vault key as base64
- android.util.Base64.encodeToString(vaultKey, android.util.Base64.NO_WRAP)
+ // If decryption succeeded, return the unlock key as base64
+ android.util.Base64.encodeToString(derivedKey, android.util.Base64.NO_WRAP)
} catch (e: Exception) {
// Password incorrect or decryption failed - intentionally return null
// We don't log the error as this is expected when password is incorrect
@@ -325,10 +327,10 @@ class VaultStore(
* Unlock the vault.
*/
fun unlockVault() {
- // A nil-to-non-nil transition means the keystore just released the key after biometric.
- val hadKeyInMemory = encryptionKey != null
+ // A nil-to-non-nil transition means the keystore just released the unlock key after biometric.
+ val hadKeyInMemory = crypto.unlockKey != null
database.unlockVault(auth.getAuthMethods())
- if (!hadKeyInMemory && encryptionKey != null) {
+ if (!hadKeyInMemory && crypto.unlockKey != null) {
markSuccessfulAuth()
}
}
@@ -455,11 +457,11 @@ class VaultStore(
}
/**
- * Attempts to get all items using only the cached encryption key.
+ * Attempts to get all items using only the unlock key held in memory.
*/
fun tryGetAllItems(callback: ItemOperationCallback): Boolean {
- if (crypto.encryptionKey == null) {
- android.util.Log.d(TAG, "Encryption key not in memory, authentication required")
+ if (crypto.unlockKey == null) {
+ android.util.Log.d(TAG, "Unlock key not in memory, authentication required")
return false
}
@@ -493,8 +495,8 @@ class VaultStore(
if (!wasBiometricEnabled && isBiometricEnabled) {
try {
- crypto.storeEncryptionKey(
- android.util.Base64.encodeToString(crypto.encryptionKey, android.util.Base64.NO_WRAP),
+ crypto.storeUnlockKey(
+ android.util.Base64.encodeToString(crypto.unlockKey, android.util.Base64.NO_WRAP),
authMethods,
)
} catch (e: Exception) {
@@ -676,18 +678,6 @@ class VaultStore(
return encryptionKey?.let { android.util.Base64.encodeToString(it, android.util.Base64.NO_WRAP) }
}
- /**
- * Adopt a new vault encryption key for this session (the sync engine swapped a password-derived key for the
- * account's VEK), persisting it to the keystore when biometrics are enabled.
- */
- fun adoptEncryptionKey(base64EncryptionKey: String) {
- // Skip if the key is the same as the current one to prevent unnecessary keystore writes and therefore prompts to user.
- if (crypto.encryptionKey?.contentEquals(android.util.Base64.decode(base64EncryptionKey, android.util.Base64.NO_WRAP)) == true) {
- return
- }
- crypto.storeEncryptionKey(base64EncryptionKey, auth.getAuthMethods())
- }
-
/**
* Forget what the sync engine learned about the stored vault (revisions, fingerprints, key chain), so the next
* sync starts from the server as if this device had never pulled. Used when the vault is discarded.
@@ -705,7 +695,7 @@ class VaultStore(
}
/**
- * Resolve and store the vault key right after login from the password-derived key (see VaultSync.resolveVaultKey).
+ * Resolve and store the vault key right after login from the unlock key (see VaultSync.resolveVaultKey).
*/
suspend fun resolveVaultKey(webApiService: net.aliasvault.app.webapi.WebApiService, derivedKeyBase64: String): String {
return sync.resolveVaultKey(webApiService, derivedKeyBase64)
@@ -916,17 +906,16 @@ class VaultStore(
* Setup PIN unlock.
*/
@Throws(Exception::class)
- fun setupPin(pinValue: String, vaultEncryptionKeyBase64: String) {
- pin.setupPin(pinValue, vaultEncryptionKeyBase64)
+ fun setupPin(pinValue: String, unlockKeyBase64: String) {
+ pin.setupPin(pinValue, unlockKeyBase64)
}
/**
- * Unlock with PIN.
+ * Unlock with PIN. Returns the unlock key the PIN protects, to open the session with.
*/
@Throws(Exception::class)
fun unlockWithPin(pinValue: String): String {
- // A PIN set up before the account moved onto the key hierarchy still holds the password-derived key.
- val key = crypto.resolveStoredUnlockKey(pin.unlockWithPin(pinValue))
+ val key = pin.unlockWithPin(pinValue)
markSuccessfulAuth()
return key
}
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.kt
index 444cbbec8..704d2f669 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
@@ -91,17 +91,17 @@ class VaultSync(
}
/**
- * Resolve the vault key right after login: the account's key chain is opened with the password-derived key and the VEK
- * is stored as the session key; a legacy account keeps the derived key. Every sync assumes the key this stored. Returns the stored key (base64).
+ * 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).
*/
suspend fun resolveVaultKey(webApiService: WebApiService, derivedKeyBase64: String): String {
val result = run("resolveVaultKey", webApiService, encryptionKey = derivedKeyBase64)
if (!result.optBoolean("success", false)) {
throw syncError(result)
}
- val key = result.optString("encryptionKey").takeIf { it.isNotEmpty() } ?: derivedKeyBase64
- vaultStore.adoptEncryptionKey(key)
- return key
+ vaultStore.storeUnlockKey(derivedKeyBase64)
+ return vaultStore.getEncryptionKeyBase64() ?: derivedKeyBase64
}
/**
@@ -166,10 +166,6 @@ class VaultSync(
if (result.has("isOfflineMode")) {
vaultStore.metadata.setOfflineMode(result.optBoolean("isOfflineMode", false))
}
- result.optJSONObject("sessionUpdates")?.let { updates ->
- updates.optString("encryptionKey").takeIf { it.isNotEmpty() }?.let { vaultStore.adoptEncryptionKey(it) }
- updates.optString("accountPrivateKey").takeIf { it.isNotEmpty() }?.let { vaultStore.accountPrivateKey = it }
- }
result.optJSONObject("emailRouting")?.let { routing ->
val metadata = VaultMetadata(
publicEmailDomains = routing.optJSONArray("publicEmailDomainList").toStringList(),
diff --git a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultSyncEngine.kt b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultSyncEngine.kt
index cdcef11e1..67e51120f 100644
--- a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultSyncEngine.kt
+++ b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultSyncEngine.kt
@@ -33,6 +33,7 @@ class VaultSyncEngine(
/** Engine state keys mirrored into the native account-key chain, so the native password unlock can unwrap it. */
private const val ENCRYPTED_ACCOUNT_KEY_STATE_KEY = "encryptedAccountKey"
private const val ENCRYPTED_VEK_STATE_KEY = "encryptedVek"
+ private const val ENCRYPTED_ACCOUNT_PRIVATE_KEY_STATE_KEY = "encryptedAccountPrivateKey"
/** Engine state key that lives in the native store instead (the login writes it there), routed on read and write. */
private const val DERIVATION_PARAMS_STATE_KEY = "encryptionKeyDerivationParams"
@@ -200,7 +201,7 @@ class VaultSyncEngine(
} else {
storageProvider.setSyncEngineState(key, JSONObject().put("v", value).toString())
}
- if (key == ENCRYPTED_ACCOUNT_KEY_STATE_KEY || key == ENCRYPTED_VEK_STATE_KEY) {
+ if (key == ENCRYPTED_ACCOUNT_KEY_STATE_KEY || key == ENCRYPTED_VEK_STATE_KEY || key == ENCRYPTED_ACCOUNT_PRIVATE_KEY_STATE_KEY) {
mirrorAccountKeyChain()
}
}
@@ -216,6 +217,7 @@ class VaultSyncEngine(
return
}
val chain = JSONObject().put("encryptedAccountKey", encryptedAccountKey).put("encryptedVek", encryptedVek)
+ (state(ENCRYPTED_ACCOUNT_PRIVATE_KEY_STATE_KEY) as? String)?.let { chain.put("encryptedAccountPrivateKey", it) }
vaultStore.storeAccountKeyChain(chain.toString())
}
@@ -225,10 +227,6 @@ class VaultSyncEngine(
private fun storeVault(command: JSONObject): JSONObject {
val encryptedBlob = command.getString("encryptedBlob")
- if (command.has("encryptionKey") && !command.isNull("encryptionKey")) {
- // The blob is encrypted under a key this session did not start with (KEK to VEK migration): adopt it first.
- vaultStore.adoptEncryptionKey(command.getString("encryptionKey"))
- }
val result = vaultStore.storeEncryptedVaultWithSyncState(
encryptedVault = encryptedBlob,
markDirty = command.optBoolean("markDirty", false),
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.kt
index f393cbc15..b7fcc5f50 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 key.
+ * The filename for the encrypted unlock 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.kt
index 2b8951e6b..a4ffd4cd9 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 testEncryptionKeyBase64 = "/9So3C83JLDIfjsF0VQOc4rz1uAFtIseW7yrUuztAD0=" // 32 bytes for AES-256
+ private val testUnlockKeyBase64 = "/9So3C83JLDIfjsF0VQOc4rz1uAFtIseW7yrUuztAD0=" // 32 bytes for AES-256
@Before
fun setup() {
@@ -29,7 +29,7 @@ class VaultStoreTest {
// Initialize the VaultStore instance with a mock file provider that
// is only used for testing purposes
vaultStore = VaultStore(TestStorageProvider(), TestKeystoreProvider())
- vaultStore.storeEncryptionKey(testEncryptionKeyBase64)
+ vaultStore.storeUnlockKey(testUnlockKeyBase64)
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.storeEncryptionKey(testEncryptionKeyBase64)
+ vaultStore.storeUnlockKey(testUnlockKeyBase64)
vaultStore.unlockVault()
// Do a query
diff --git a/apps/mobile-app/app/login.tsx b/apps/mobile-app/app/login.tsx
index 990396241..e763ad328 100644
--- a/apps/mobile-app/app/login.tsx
+++ b/apps/mobile-app/app/login.tsx
@@ -31,7 +31,7 @@ import { useDialog } from '@/context/DialogContext';
import { useWebApi } from '@/context/WebApiContext';
import NativeVaultManager from '@/specs/NativeVaultManager';
-import type { EncryptionKeyDerivationParams } from '@aliasvault/models/metadata';
+import type { UnlockKeyDerivationParams } from '@aliasvault/models/metadata';
import type { LoginResponse } from '@aliasvault/models/webapi';
/**
@@ -239,7 +239,7 @@ export default function LoginScreen() : React.ReactNode {
* @param refreshToken - The refresh token to use for the vault
* @param passwordHashBase64 - The password hash base64
* @param initiateLoginResponse - The initiate login response
- * @param encryptionKeyDerivationParams - The encryption key derivation parameters
+ * @param unlockKeyDerivationParams - The encryption key derivation parameters
*/
const continueProcessVaultResponse = async (
token: string,
@@ -247,7 +247,7 @@ export default function LoginScreen() : React.ReactNode {
passwordHashBase64: string,
initiateLoginResponse: LoginResponse
) : Promise<void> => {
- const encryptionKeyDerivationParams : EncryptionKeyDerivationParams = {
+ const unlockKeyDerivationParams : UnlockKeyDerivationParams = {
encryptionType: initiateLoginResponse.encryptionType,
encryptionSettings: initiateLoginResponse.encryptionSettings,
salt: initiateLoginResponse.salt,
@@ -258,12 +258,13 @@ export default function LoginScreen() : React.ReactNode {
* the vault and store it (including metadata) through native code.
*/
await authContext.setAuthTokens(SrpAuthService.normalizeUsername(credentials.username), token, refreshToken);
- await dbContext.storeEncryptionKeyDerivationParams(encryptionKeyDerivationParams);
+ await dbContext.storeUnlockKeyDerivationParams(unlockKeyDerivationParams);
/*
- * The derived key is the password KEK. The Rust core opens the account's key chain with it (fetched from the
- * server, or the cached one when offline) and stores the VEK as the vault key; a legacy account without a
- * chain keeps the KEK. Every sync assumes the key stored here.
+ * The derived key is the KEK/unlock key. The Rust core opens the account's key chain with it (fetched from the
+ * server, or the cached one when offline) and caches the chain as-is. The session holds the VEK and the account
+ * private key, while biometrics and PIN keep the KEK and open the chain again on every unlock; a legacy account
+ * without a chain uses the KEK as the vault key.
*/
await NativeVaultManager.resolveVaultKey(passwordHashBase64);
diff --git a/apps/mobile-app/app/unlock.tsx b/apps/mobile-app/app/unlock.tsx
index a7f881af4..52d130e70 100644
--- a/apps/mobile-app/app/unlock.tsx
+++ b/apps/mobile-app/app/unlock.tsx
@@ -27,7 +27,7 @@ import NativeVaultManager from '@/specs/NativeVaultManager';
* Unlock screen.
*/
export default function UnlockScreen() : React.ReactNode {
- const { isLoggedIn, username, getEncryptionKeyDerivationParams } = useApp();
+ const { isLoggedIn, username, getUnlockKeyDerivationParams } = useApp();
const { logoutUserInitiated, logoutForced } = useLogout();
const dbContext = useDb();
const [isLoading, setIsLoading] = useState(true);
@@ -50,14 +50,14 @@ export default function UnlockScreen() : React.ReactNode {
* If not, we can't unlock the vault so logout instead to redirect user to login screen.
*/
const getKeyDerivationParams = useCallback(async () : Promise<{ salt: string; encryptionType: string; encryptionSettings: string } | null> => {
- const params = await getEncryptionKeyDerivationParams();
+ const params = await getUnlockKeyDerivationParams();
if (!params) {
// No params means corrupted state - force logout without confirmation
await logoutForced();
return null;
}
return params;
- }, [logoutForced, getEncryptionKeyDerivationParams]);
+ }, [logoutForced, getUnlockKeyDerivationParams]);
useEffect(() => {
let isMounted = true;
diff --git a/apps/mobile-app/context/AppContext.tsx b/apps/mobile-app/context/AppContext.tsx
index 9cb314e5a..a3bbf411d 100644
--- a/apps/mobile-app/context/AppContext.tsx
+++ b/apps/mobile-app/context/AppContext.tsx
@@ -23,7 +23,7 @@ type AppContextType = {
setAutoLockTimeout: (timeout: number) => Promise<void>;
setOfflineMode: (isOffline: boolean) => void;
verifyPassword: (password: string) => Promise<string | null>;
- getEncryptionKeyDerivationParams: () => Promise<{ salt: string; encryptionType: string; encryptionSettings: string } | null>;
+ getUnlockKeyDerivationParams: () => Promise<{ salt: string; encryptionType: string; encryptionSettings: string } | null>;
// Autofill methods
shouldShowAutofillReminder: boolean;
markAutofillConfigured: () => Promise<void>;
@@ -108,7 +108,7 @@ export const AppProvider: React.FC<{ children: React.ReactNode }> = ({ children
setAutoLockTimeout: auth.setAutoLockTimeout,
setOfflineMode: auth.setOfflineMode,
verifyPassword: auth.verifyPassword,
- getEncryptionKeyDerivationParams: auth.getEncryptionKeyDerivationParams,
+ getUnlockKeyDerivationParams: auth.getUnlockKeyDerivationParams,
markAutofillConfigured: auth.markAutofillConfigured,
}), [
auth.isInitialized,
@@ -124,7 +124,7 @@ export const AppProvider: React.FC<{ children: React.ReactNode }> = ({ children
auth.setAutoLockTimeout,
auth.setOfflineMode,
auth.verifyPassword,
- auth.getEncryptionKeyDerivationParams,
+ auth.getUnlockKeyDerivationParams,
auth.markAutofillConfigured,
logout
]);
diff --git a/apps/mobile-app/context/AuthContext.tsx b/apps/mobile-app/context/AuthContext.tsx
index b10cbda5c..079a5ebd0 100644
--- a/apps/mobile-app/context/AuthContext.tsx
+++ b/apps/mobile-app/context/AuthContext.tsx
@@ -36,7 +36,7 @@ type AuthContextType = {
setAutoLockTimeout: (timeout: number) => Promise<void>;
setOfflineMode: (isOffline: boolean) => void;
verifyPassword: (password: string) => Promise<string | null>;
- getEncryptionKeyDerivationParams: () => Promise<{ salt: string; encryptionType: string; encryptionSettings: string } | null>;
+ getUnlockKeyDerivationParams: () => Promise<{ salt: string; encryptionType: string; encryptionSettings: string } | null>;
// Autofill methods
shouldShowAutofillReminder: boolean;
markAutofillConfigured: () => Promise<void>;
@@ -234,17 +234,17 @@ export const AuthProvider: React.FC<{
* Get the encryption key derivation parameters from native storage.
* Returns parsed parameters or null if not available.
*/
- const getEncryptionKeyDerivationParams = useCallback(async (): Promise<{
+ const getUnlockKeyDerivationParams = useCallback(async (): Promise<{
salt: string;
encryptionType: string;
encryptionSettings: string;
} | null> => {
try {
- const encryptionKeyDerivationParams = await NativeVaultManager.getEncryptionKeyDerivationParams();
- if (!encryptionKeyDerivationParams) {
+ const unlockKeyDerivationParams = await NativeVaultManager.getUnlockKeyDerivationParams();
+ if (!unlockKeyDerivationParams) {
return null;
}
- return JSON.parse(encryptionKeyDerivationParams);
+ return JSON.parse(unlockKeyDerivationParams);
} catch (error) {
console.error('Failed to get encryption key derivation params:', error);
return null;
@@ -256,7 +256,7 @@ export const AuthProvider: React.FC<{
*/
const verifyPassword = useCallback(async (password: string): Promise<string | null> => {
// Get the key derivation parameters
- const params = await getEncryptionKeyDerivationParams();
+ const params = await getUnlockKeyDerivationParams();
if (!params) {
throw new Error('Failed to verify current password. Please try again.');
}
@@ -272,13 +272,13 @@ export const AuthProvider: React.FC<{
const currentPasswordHashBase64 = Buffer.from(passwordHash).toString('base64');
// Check if the current password is correct
- const isValid = await dbContext.verifyEncryptionKey(currentPasswordHashBase64);
+ const isValid = await dbContext.verifyUnlockKey(currentPasswordHashBase64);
if (!isValid) {
return null;
}
return currentPasswordHashBase64;
- }, [dbContext, getEncryptionKeyDerivationParams]);
+ }, [dbContext, getUnlockKeyDerivationParams]);
/**
* Load autofill state from storage
@@ -325,7 +325,7 @@ export const AuthProvider: React.FC<{
setAutoLockTimeout,
markAutofillConfigured,
verifyPassword,
- getEncryptionKeyDerivationParams,
+ getUnlockKeyDerivationParams,
setOfflineMode,
}), [
isLoggedIn,
@@ -343,7 +343,7 @@ export const AuthProvider: React.FC<{
setAutoLockTimeout,
markAutofillConfigured,
verifyPassword,
- getEncryptionKeyDerivationParams,
+ getUnlockKeyDerivationParams,
setOfflineMode,
]);
diff --git a/apps/mobile-app/context/DbContext.tsx b/apps/mobile-app/context/DbContext.tsx
index 127026aad..13384bb23 100644
--- a/apps/mobile-app/context/DbContext.tsx
+++ b/apps/mobile-app/context/DbContext.tsx
@@ -1,6 +1,6 @@
import React, { createContext, useContext, useState, useEffect, useCallback, useMemo } from 'react';
-import type { EncryptionKeyDerivationParams, VaultMetadata } from '@aliasvault/models/metadata';
+import type { UnlockKeyDerivationParams, VaultMetadata } from '@aliasvault/models/metadata';
import EncryptionUtility from '@/utils/EncryptionUtility';
import SqliteClient from '@/utils/SqliteClient';
@@ -25,14 +25,14 @@ type DbContextType = {
*/
shouldSuppressEmailErrors: () => boolean;
refreshSyncState: () => Promise<void>;
- storeEncryptionKey: (derivedKey: string) => Promise<void>;
- storeEncryptionKeyDerivationParams: (keyDerivationParams: EncryptionKeyDerivationParams) => Promise<void>;
+ storeUnlockKey: (derivedKey: string) => Promise<void>;
+ storeUnlockKeyDerivationParams: (keyDerivationParams: UnlockKeyDerivationParams) => Promise<void>;
requiresLegacySqliteBlobMigration: () => Promise<boolean>;
hasPendingMigrations: () => Promise<boolean>;
clearDatabase: () => void;
getVaultMetadata: () => Promise<VaultMetadata | null>;
testDatabaseConnection: (derivedKey: string, persistToKeychain?: boolean) => Promise<boolean>;
- verifyEncryptionKey: (derivedKey: string) => Promise<boolean>;
+ verifyUnlockKey: (derivedKey: string) => Promise<boolean>;
unlockVault: () => Promise<boolean>;
checkStoredVault: () => Promise<void>;
setDatabaseAvailable: () => void;
@@ -100,13 +100,13 @@ export const DbProvider: React.FC<{ children: React.ReactNode }> = ({ children }
}, []);
/**
- * Store the encryption key in the Native module (in memory and optionally keychain).
+ * Store the unlock key (the password-derived KEK) in the Native module (in memory and optionally keychain). The
+ * native module opens the account key chain with it, which gives the vault encryption key of the session.
*
- * @param derivedKey The derived encryption key
- * @param keyDerivationParams The key derivation parameters (used for deriving the encryption key from the plain text password in the unlock screen)
+ * @param derivedKey The password-derived unlock key
*/
- const storeEncryptionKey = useCallback(async (derivedKey: string) => {
- await sqliteClient.storeEncryptionKey(derivedKey
+ const storeUnlockKey = useCallback(async (derivedKey: string) => {
+ await sqliteClient.storeUnlockKey(derivedKey
);
}, [sqliteClient]);
@@ -115,8 +115,8 @@ export const DbProvider: React.FC<{ children: React.ReactNode }> = ({ children }
*
* @param keyDerivationParams The key derivation parameters
*/
- const storeEncryptionKeyDerivationParams = useCallback(async (keyDerivationParams: EncryptionKeyDerivationParams) => {
- await sqliteClient.storeEncryptionKeyDerivationParams(keyDerivationParams);
+ const storeUnlockKeyDerivationParams = useCallback(async (keyDerivationParams: UnlockKeyDerivationParams) => {
+ await sqliteClient.storeUnlockKeyDerivationParams(keyDerivationParams);
}, [sqliteClient]);
/**
@@ -249,15 +249,15 @@ export const DbProvider: React.FC<{ children: React.ReactNode }> = ({ children }
}, [sqliteClient]);
/**
- * Test if the database is working with the provided (to be stored) encryption key by performing a simple query.
+ * Test if the database is working with the provided (to be stored) unlock key by performing a simple query.
* Uses two-step process: first init key in memory, verify it works, then persist to keystore.
* This prevents overwriting a valid key with an invalid one if user enters wrong password.
- * @param derivedKey The encryption key to test with
+ * @param derivedKey The unlock key (the password-derived KEK) to test with
* @returns true if the database is working
* @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.storeEncryptionKeyInMemory(derivedKey);
+ await sqliteClient.storeUnlockKeyInMemory(derivedKey);
await unlockVault();
@@ -271,7 +271,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.storeEncryptionKey(derivedKey);
+ await sqliteClient.storeUnlockKey(derivedKey);
}
return true;
}
@@ -280,20 +280,20 @@ export const DbProvider: React.FC<{ children: React.ReactNode }> = ({ children }
}, [sqliteClient, unlockVault]);
/**
- * Verify if the provided encryption key is valid.
- * @param derivedKey The encryption key to verify
+ * Verify if the provided unlock key is valid.
+ * @param derivedKey The unlock key (the password-derived KEK) to verify
* @returns true if the key is valid, false if invalid (wrong password)
*/
- const verifyEncryptionKey = useCallback(async (derivedKey: string): Promise<boolean> => {
+ const verifyUnlockKey = useCallback(async (derivedKey: string): Promise<boolean> => {
try {
- await sqliteClient.storeEncryptionKeyInMemory(derivedKey);
+ await sqliteClient.storeUnlockKeyInMemory(derivedKey);
await unlockVault();
const version = await sqliteClient.getDatabaseVersion();
return !!(version && version.version && version.version.length > 0);
} catch (error) {
// Unlock failed - likely wrong password/key
- console.error('verifyEncryptionKey failed:', error);
+ console.error('verifyUnlockKey failed:', error);
return false;
}
}, [sqliteClient, unlockVault]);
@@ -317,13 +317,13 @@ export const DbProvider: React.FC<{ children: React.ReactNode }> = ({ children }
clearDatabase,
getVaultMetadata,
testDatabaseConnection,
- verifyEncryptionKey,
+ verifyUnlockKey,
unlockVault,
- storeEncryptionKey,
- storeEncryptionKeyDerivationParams,
+ storeUnlockKey,
+ storeUnlockKeyDerivationParams,
checkStoredVault,
setDatabaseAvailable,
- }), [sqliteClient, dbInitialized, dbAvailable, isDirty, isSyncing, isUploading, isOffline, setIsSyncing, setIsUploading, setIsOffline, shouldSuppressEmailErrors, refreshSyncState, requiresLegacySqliteBlobMigration, hasPendingMigrations, clearDatabase, getVaultMetadata, testDatabaseConnection, verifyEncryptionKey, unlockVault, storeEncryptionKey, storeEncryptionKeyDerivationParams, checkStoredVault, setDatabaseAvailable]);
+ }), [sqliteClient, dbInitialized, dbAvailable, isDirty, isSyncing, isUploading, isOffline, setIsSyncing, setIsUploading, setIsOffline, shouldSuppressEmailErrors, refreshSyncState, requiresLegacySqliteBlobMigration, hasPendingMigrations, clearDatabase, getVaultMetadata, testDatabaseConnection, verifyUnlockKey, unlockVault, storeUnlockKey, storeUnlockKeyDerivationParams, checkStoredVault, setDatabaseAvailable]);
return (
<DbContext.Provider value={contextValue}>
diff --git a/apps/mobile-app/hooks/useVaultMutate.ts b/apps/mobile-app/hooks/useVaultMutate.ts
index f35ab94cf..2b758c0ba 100644
--- a/apps/mobile-app/hooks/useVaultMutate.ts
+++ b/apps/mobile-app/hooks/useVaultMutate.ts
@@ -4,7 +4,7 @@ import { useCallback, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
import Toast from 'react-native-toast-message';
-import type { EncryptionKeyDerivationParams } from '@aliasvault/models/metadata';
+import type { UnlockKeyDerivationParams } from '@aliasvault/models/metadata';
import type { PasswordChangeInitiateResponse, Vault, VaultPasswordChangeRequest } from '@aliasvault/models/webapi';
import { FieldKey, getFieldValue } from '@aliasvault/models/vault';
import EncryptionUtility from '@/utils/EncryptionUtility';
@@ -217,14 +217,14 @@ export function useVaultMutate() : {
// Store the new encryption key and derivation parameters locally
try {
- const newEncryptionKeyDerivationParams : EncryptionKeyDerivationParams = {
+ const newUnlockKeyDerivationParams : UnlockKeyDerivationParams = {
encryptionType: data.encryptionType,
encryptionSettings: data.encryptionSettings,
salt: newSalt,
};
- await dbContext.storeEncryptionKey(Buffer.from(newPasswordHash).toString('base64'));
- await dbContext.storeEncryptionKeyDerivationParams(newEncryptionKeyDerivationParams);
+ await dbContext.storeUnlockKey(Buffer.from(newPasswordHash).toString('base64'));
+ await dbContext.storeUnlockKeyDerivationParams(newUnlockKeyDerivationParams);
/**
* Persist the new encrypted database with the new encryption key by starting and committing a transaction.
diff --git a/apps/mobile-app/ios/Autofill/CredentialProviderViewController.swift b/apps/mobile-app/ios/Autofill/CredentialProviderViewController.swift
index 4f3c1909d..d6e717f99 100644
--- a/apps/mobile-app/ios/Autofill/CredentialProviderViewController.swift
+++ b/apps/mobile-app/ios/Autofill/CredentialProviderViewController.swift
@@ -239,10 +239,10 @@ public class CredentialProviderViewController: ASCredentialProviderViewControlle
guard let self = self else { return }
// Attempt to unlock with PIN
- let encryptionKeyBase64 = try vaultStore.unlockWithPin(pin)
+ let unlockKeyBase64 = try vaultStore.unlockWithPin(pin)
- // Store the encryption key and unlock
- try vaultStore.storeEncryptionKey(base64Key: encryptionKeyBase64)
+ // Open the session with the unlock key and unlock
+ try vaultStore.storeUnlockKey(base64Key: unlockKeyBase64)
try vaultStore.unlockVault()
// Process the credential request
diff --git a/apps/mobile-app/ios/Autofill/UnlockCoordinator.swift b/apps/mobile-app/ios/Autofill/UnlockCoordinator.swift
index 21f3bcb0f..7029a83e9 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 encryptionKeyBase64 = try self.vaultStore.unlockWithPin(pin)
+ let unlockKeyBase64 = try self.vaultStore.unlockWithPin(pin)
- // Store the encryption key in memory
- try self.vaultStore.storeEncryptionKey(base64Key: encryptionKeyBase64)
+ // Open the session with the unlock key
+ try self.vaultStore.storeUnlockKey(base64Key: unlockKeyBase64)
// Now unlock the vault with the key in memory
try self.vaultStore.unlockVault()
diff --git a/apps/mobile-app/ios/NativeVaultManager/RCTNativeVaultManager.mm b/apps/mobile-app/ios/NativeVaultManager/RCTNativeVaultManager.mm
index b2ffdc4b8..94975f988 100644
--- a/apps/mobile-app/ios/NativeVaultManager/RCTNativeVaultManager.mm
+++ b/apps/mobile-app/ios/NativeVaultManager/RCTNativeVaultManager.mm
@@ -97,24 +97,24 @@
[vaultManager storeMetadata:metadata resolver:resolve rejecter:reject];
}
-- (void)storeEncryptionKeyInMemory:(NSString *)base64EncryptionKey resolve:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject {
- [vaultManager storeEncryptionKeyInMemory:base64EncryptionKey resolver:resolve rejecter:reject];
+- (void)storeUnlockKeyInMemory:(NSString *)base64UnlockKey resolve:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject {
+ [vaultManager storeUnlockKeyInMemory:base64UnlockKey resolver:resolve rejecter:reject];
}
-- (void)storeEncryptionKey:(NSString *)base64EncryptionKey resolve:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject {
- [vaultManager storeEncryptionKey:base64EncryptionKey resolver:resolve rejecter:reject];
+- (void)storeUnlockKey:(NSString *)base64UnlockKey resolve:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject {
+ [vaultManager storeUnlockKey:base64UnlockKey resolver:resolve rejecter:reject];
}
- (void)clearEncryptionKeyFromMemory:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject {
[vaultManager clearEncryptionKeyFromMemory:resolve rejecter:reject];
}
-- (void)storeEncryptionKeyDerivationParams:(NSString *)keyDerivationParams resolve:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject {
- [vaultManager storeEncryptionKeyDerivationParams:keyDerivationParams resolver:resolve rejecter:reject];
+- (void)storeUnlockKeyDerivationParams:(NSString *)keyDerivationParams resolve:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject {
+ [vaultManager storeUnlockKeyDerivationParams:keyDerivationParams resolver:resolve rejecter:reject];
}
-- (void)getEncryptionKeyDerivationParams:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject {
- [vaultManager getEncryptionKeyDerivationParams:resolve rejecter:reject];
+- (void)getUnlockKeyDerivationParams:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject {
+ [vaultManager getUnlockKeyDerivationParams:resolve rejecter:reject];
}
- (void)storeAccountKeyChain:(NSString *)chainJson resolve:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject {
diff --git a/apps/mobile-app/ios/NativeVaultManager/VaultManager.swift b/apps/mobile-app/ios/NativeVaultManager/VaultManager.swift
index f11be85e0..7561b5e7e 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 {
}
}
- /// Store encryption key in memory only (no keychain persistence).
+ /// Open a session in memory with the unlock key (the password-derived KEK), without keychain persistence.
/// Use this to test if a password-derived key is valid before persisting.
@objc
- func storeEncryptionKeyInMemory(_ base64EncryptionKey: String,
+ func storeUnlockKeyInMemory(_ base64UnlockKey: String,
resolver resolve: @escaping RCTPromiseResolveBlock,
rejecter reject: @escaping RCTPromiseRejectBlock) {
do {
- try vaultStore.storeEncryptionKeyInMemory(base64Key: base64EncryptionKey)
+ try vaultStore.storeUnlockKeyInMemory(base64Key: base64UnlockKey)
resolve(nil)
} catch {
- reject("ERR_STORE_KEY_MEMORY", "Failed to store encryption key in memory: \(error.localizedDescription)", error)
+ reject("ERR_STORE_KEY_MEMORY", "Failed to store unlock key in memory: \(error.localizedDescription)", error)
}
}
- /// Store encryption key in memory AND persist to keychain if Face ID is enabled.
+ /// Open a session with the unlock key (the password-derived KEK) AND persist it to keychain if Face ID is enabled.
@objc
- func storeEncryptionKey(_ base64EncryptionKey: String,
+ func storeUnlockKey(_ base64UnlockKey: String,
resolver resolve: @escaping RCTPromiseResolveBlock,
rejecter reject: @escaping RCTPromiseRejectBlock) {
do {
- try vaultStore.storeEncryptionKey(base64Key: base64EncryptionKey)
+ try vaultStore.storeUnlockKey(base64Key: base64UnlockKey)
resolve(nil)
} catch {
- reject("KEYCHAIN_ERROR", "Failed to store encryption key: \(error.localizedDescription)", error)
+ reject("KEYCHAIN_ERROR", "Failed to store unlock key: \(error.localizedDescription)", error)
}
}
@@ -99,11 +99,11 @@ public class VaultManager: NSObject {
}
@objc
- func storeEncryptionKeyDerivationParams(_ keyDerivationParams: String,
+ func storeUnlockKeyDerivationParams(_ keyDerivationParams: String,
resolver resolve: @escaping RCTPromiseResolveBlock,
rejecter reject: @escaping RCTPromiseRejectBlock) {
do {
- try vaultStore.storeEncryptionKeyDerivationParams(keyDerivationParams)
+ try vaultStore.storeUnlockKeyDerivationParams(keyDerivationParams)
resolve(nil)
} catch {
reject("KEYCHAIN_ERROR", "Failed to store encryption key derivation params: \(error.localizedDescription)", error)
@@ -111,9 +111,9 @@ public class VaultManager: NSObject {
}
@objc
- func getEncryptionKeyDerivationParams(_ resolve: @escaping RCTPromiseResolveBlock,
+ func getUnlockKeyDerivationParams(_ resolve: @escaping RCTPromiseResolveBlock,
rejecter reject: @escaping RCTPromiseRejectBlock) {
- if let params = vaultStore.getEncryptionKeyDerivationParams() {
+ if let params = vaultStore.getUnlockKeyDerivationParams() {
resolve(params)
} else {
resolve(nil)
@@ -945,10 +945,10 @@ public class VaultManager: NSObject {
}
// Unlock vault with PIN
- let encryptionKeyBase64 = try self.vaultStore.unlockWithPin(pin)
+ let unlockKeyBase64 = try self.vaultStore.unlockWithPin(pin)
- // Store the encryption key in memory
- try self.vaultStore.storeEncryptionKey(base64Key: encryptionKeyBase64)
+ // Open the session with the unlock key
+ try self.vaultStore.storeUnlockKey(base64Key: unlockKeyBase64)
// Now unlock the vault with the key in memory
try self.vaultStore.unlockVault()
@@ -1010,13 +1010,13 @@ public class VaultManager: NSObject {
throw NSError(domain: "VaultManager", code: -1, userInfo: [NSLocalizedDescriptionKey: "VaultManager instance deallocated"])
}
- // Verify password and get encryption key
- guard let encryptionKeyBase64 = self.vaultStore.verifyPassword(password) else {
+ // Verify password and get the unlock key
+ guard let unlockKeyBase64 = self.vaultStore.verifyPassword(password) else {
throw NSError(domain: "VaultManager", code: -1, userInfo: [NSLocalizedDescriptionKey: "Incorrect password"])
}
- // Store encryption key in memory only
- try self.vaultStore.storeEncryptionKeyInMemory(base64Key: encryptionKeyBase64)
+ // Open the session in memory only
+ try self.vaultStore.storeUnlockKeyInMemory(base64Key: unlockKeyBase64)
// Unlock the vault
try self.vaultStore.unlockVault()
@@ -1361,12 +1361,12 @@ public class VaultManager: NSObject {
throw NSError(domain: "VaultManager", code: -1, userInfo: [NSLocalizedDescriptionKey: "VaultManager instance deallocated"])
}
- // Verify password and get encryption key
- guard let encryptionKey = try self.vaultStore.verifyPassword(password) else {
+ // Verify password and get the unlock key
+ guard let unlockKeyBase64 = try self.vaultStore.verifyPassword(password) else {
throw NSError(domain: "VaultManager", code: -1, userInfo: [NSLocalizedDescriptionKey: "Incorrect password"])
}
- try self.vaultStore.storeEncryptionKeyInMemory(base64Key: encryptionKey)
+ try self.vaultStore.storeUnlockKeyInMemory(base64Key: unlockKeyBase64)
// Success - dismiss and resolve
await MainActor.run {
diff --git a/apps/mobile-app/ios/VaultModels/EncryptionKeyDerivationParams.swift b/apps/mobile-app/ios/VaultModels/UnlockKeyDerivationParams.swift
similarity index 86%
rename from apps/mobile-app/ios/VaultModels/EncryptionKeyDerivationParams.swift
rename to apps/mobile-app/ios/VaultModels/UnlockKeyDerivationParams.swift
index 43a07cd73..8174ed73a 100644
--- a/apps/mobile-app/ios/VaultModels/EncryptionKeyDerivationParams.swift
+++ b/apps/mobile-app/ios/VaultModels/UnlockKeyDerivationParams.swift
@@ -1,6 +1,6 @@
import Foundation
-public struct EncryptionKeyDerivationParams: Codable {
+public struct UnlockKeyDerivationParams: Codable {
public var encryptionType: String?
public var encryptionSettings: String?
public var salt: String?
diff --git a/apps/mobile-app/ios/VaultStoreKit/Services/VaultSync.swift b/apps/mobile-app/ios/VaultStoreKit/Services/VaultSync.swift
index 85a7eeb5c..9aee3f9fc 100644
--- a/apps/mobile-app/ios/VaultStoreKit/Services/VaultSync.swift
+++ b/apps/mobile-app/ios/VaultStoreKit/Services/VaultSync.swift
@@ -73,17 +73,16 @@ internal final class VaultSync {
return VaultVersionCheckResult(isNewVersionAvailable: result["hasNewerVault"] as? Bool ?? false, syncState: vaultStore.getSyncState())
}
- /// Resolve the vault key right after login: the account's key chain is opened with the password-derived key and the
- /// VEK is stored as the session key; a legacy account keeps the derived key. Every sync assumes the key this stored.
- /// Returns the stored key (base64).
+ /// Resolve the vault key right after login: the account's key chain is opened with the password-derived key (KEK)
+ /// and cached as-is. The session then opens from that chain like every later unlock, and the keychain keeps the
+ /// KEK; a legacy account has no chain and its KEK is the vault 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)
}
- let key = result["encryptionKey"] as? String ?? derivedKeyBase64
- try vaultStore.storeEncryptionKey(base64Key: key)
- return key
+ try vaultStore.storeUnlockKey(base64Key: derivedKeyBase64)
+ return try vaultStore.getEncryptionKeyBase64()
}
/// Classify the pending manifest migration as the engine sees it: `none`, `schema-rebuild` (runs unattended) or
@@ -140,14 +139,6 @@ internal final class VaultSync {
if let offline = result["isOfflineMode"] as? Bool {
vaultStore.setOfflineMode(offline)
}
- if let updates = result["sessionUpdates"] as? [String: Any] {
- if let newKey = updates["encryptionKey"] as? String {
- try? vaultStore.adoptEncryptionKey(base64Key: newKey)
- }
- if let privateKey = updates["accountPrivateKey"] as? String {
- vaultStore.accountPrivateKey = privateKey
- }
- }
if let routing = result["emailRouting"] as? [String: Any] {
let metadata = VaultMetadata(
publicEmailDomains: routing["publicEmailDomainList"] as? [String] ?? [],
diff --git a/apps/mobile-app/ios/VaultStoreKit/Services/VaultSyncEngine.swift b/apps/mobile-app/ios/VaultStoreKit/Services/VaultSyncEngine.swift
index 0437e6404..e6d859441 100644
--- a/apps/mobile-app/ios/VaultStoreKit/Services/VaultSyncEngine.swift
+++ b/apps/mobile-app/ios/VaultStoreKit/Services/VaultSyncEngine.swift
@@ -15,6 +15,7 @@ public final class VaultSyncEngine {
/// Engine state keys mirrored into the native account-key chain, so the native password unlock can unwrap it.
private static let encryptedAccountKeyStateKey = "encryptedAccountKey"
private static let encryptedVekStateKey = "encryptedVek"
+ private static let encryptedAccountPrivateKeyStateKey = "encryptedAccountPrivateKey"
/// Engine state key that lives in the native store instead (the login writes it there), routed on read and write.
private static let derivationParamsStateKey = "encryptionKeyDerivationParams"
@@ -174,7 +175,7 @@ public final class VaultSyncEngine {
private func state(forKey key: String) -> Any? {
if key == Self.derivationParamsStateKey {
- guard let json = vaultStore.getEncryptionKeyDerivationParams(), let data = json.data(using: .utf8) else { return nil }
+ guard let json = vaultStore.getUnlockKeyDerivationParams(), let data = json.data(using: .utf8) else { return nil }
return try? JSONSerialization.jsonObject(with: data, options: [.fragmentsAllowed])
}
return Self.persistedState(forKey: key, in: vaultStore.userDefaults)
@@ -191,7 +192,7 @@ public final class VaultSyncEngine {
private func setState(_ value: Any?, forKey key: String) {
if key == Self.derivationParamsStateKey {
if let value = value, !(value is NSNull), let data = try? JSONSerialization.data(withJSONObject: value), let json = String(data: data, encoding: .utf8) {
- try? vaultStore.storeEncryptionKeyDerivationParams(json)
+ try? vaultStore.storeUnlockKeyDerivationParams(json)
}
return
}
@@ -200,7 +201,7 @@ public final class VaultSyncEngine {
} else {
vaultStore.userDefaults.removeObject(forKey: Self.statePrefix + key)
}
- if key == Self.encryptedAccountKeyStateKey || key == Self.encryptedVekStateKey {
+ if [Self.encryptedAccountKeyStateKey, Self.encryptedVekStateKey, Self.encryptedAccountPrivateKeyStateKey].contains(key) {
mirrorAccountKeyChain()
}
}
@@ -218,7 +219,10 @@ public final class VaultSyncEngine {
vaultStore.storeAccountKeyChain(nil)
return
}
- let chain: [String: String] = ["encryptedAccountKey": encryptedAccountKey, "encryptedVek": encryptedVek]
+ var chain: [String: String] = ["encryptedAccountKey": encryptedAccountKey, "encryptedVek": encryptedVek]
+ if let encryptedAccountPrivateKey = state(forKey: Self.encryptedAccountPrivateKeyStateKey) as? String {
+ chain["encryptedAccountPrivateKey"] = encryptedAccountPrivateKey
+ }
vaultStore.storeAccountKeyChain(try? Self.serializeJson(chain))
}
@@ -228,10 +232,6 @@ public final class VaultSyncEngine {
guard let encryptedBlob = command["encryptedBlob"] as? String else {
throw AppError.vaultStoreFailed(message: "vaultStore command without a blob")
}
- if let newKey = command["encryptionKey"] as? String {
- // The blob is encrypted under a key this session did not start with (KEK to VEK migration): adopt it first.
- try vaultStore.adoptEncryptionKey(base64Key: newKey)
- }
let result = try vaultStore.storeEncryptedVaultWithSyncState(
encryptedVault: encryptedBlob,
markDirty: command["markDirty"] as? Bool ?? false,
diff --git a/apps/mobile-app/ios/VaultStoreKit/VaultStore+Auth.swift b/apps/mobile-app/ios/VaultStoreKit/VaultStore+Auth.swift
index dcf613985..51a2e980f 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 encryption key in memory to keychain")
+ print("Face ID is now enabled, persisting unlock key in memory to keychain")
do {
- guard let keyData = self.encryptionKey else {
- print("Encryption key is empty, skipping keychain persistence")
+ guard let keyData = self.unlockKey else {
+ print("Unlock 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.swift
index a349a1682..38a64e3aa 100644
--- a/apps/mobile-app/ios/VaultStoreKit/VaultStore+Cache.swift
+++ b/apps/mobile-app/ios/VaultStoreKit/VaultStore+Cache.swift
@@ -4,11 +4,10 @@ import VaultUtils
/// Extension for the VaultStore class to handle cache management
extension VaultStore {
- /// Clear the memory - remove the encryption key and decrypted database from memory
+ /// Clear the memory - remove the unlock key and decrypted database from memory
public func clearCache() {
- print("Clearing cache - removing encryption key and decrypted database from memory")
- self.encryptionKey = nil
- self.accountPrivateKey = nil
+ print("Clearing cache - removing unlock key and decrypted database from memory")
+ self.unlockKey = nil
self.dbConnection = nil
clearLastSuccessfulAuth()
}
@@ -21,8 +20,7 @@ extension VaultStore {
print("Clearing session - preserving vault data for recovery")
// Clear in-memory data only
- self.encryptionKey = nil
- self.accountPrivateKey = nil
+ self.unlockKey = nil
self.dbConnection = nil
clearLastSuccessfulAuth()
@@ -59,7 +57,7 @@ extension VaultStore {
self.userDefaults.removeObject(forKey: VaultConstants.vaultMetadataKey)
self.userDefaults.removeObject(forKey: VaultConstants.authMethodsKey)
self.userDefaults.removeObject(forKey: VaultConstants.autoLockTimeoutKey)
- self.userDefaults.removeObject(forKey: VaultConstants.encryptionKeyDerivationParamsKey)
+ self.userDefaults.removeObject(forKey: VaultConstants.unlockKeyDerivationParamsKey)
self.userDefaults.removeObject(forKey: VaultConstants.accountKeyChainKey)
self.userDefaults.removeObject(forKey: VaultConstants.usernameKey)
self.userDefaults.removeObject(forKey: VaultConstants.offlineModeKey)
@@ -80,8 +78,7 @@ extension VaultStore {
print("Cleared UserDefaults")
// Clear the cache to remove all in-memory data
- self.encryptionKey = nil
- self.accountPrivateKey = nil
+ self.unlockKey = nil
self.dbConnection = nil
self.enabledAuthMethods = []
self.autoLockTimeout = VaultConstants.defaultAutoLockTimeout
diff --git a/apps/mobile-app/ios/VaultStoreKit/VaultStore+Crypto.swift b/apps/mobile-app/ios/VaultStoreKit/VaultStore+Crypto.swift
index 78152cecc..f44a2e13d 100644
--- a/apps/mobile-app/ios/VaultStoreKit/VaultStore+Crypto.swift
+++ b/apps/mobile-app/ios/VaultStoreKit/VaultStore+Crypto.swift
@@ -23,60 +23,74 @@ extension VaultStore {
return derivedKey
}
- /// Store the encryption key in memory only (no keychain persistence).
+ /// Open a session in memory with the unlock key (the password-derived KEK), without keychain persistence.
/// Use this to test if a password-derived key is valid before persisting.
- public func storeEncryptionKeyInMemory(base64Key: String) throws {
+ public func storeUnlockKeyInMemory(base64Key: String) throws {
guard let keyData = Data(base64Encoded: base64Key) else {
throw NSError(domain: "VaultStore", code: 6, userInfo: [NSLocalizedDescriptionKey: "Invalid base64 key"])
}
- guard keyData.count == 32 else {
- throw NSError(domain: "VaultStore", code: 7, userInfo: [NSLocalizedDescriptionKey: "Invalid key length. Expected 32 bytes"])
- }
-
- self.encryptionKey = keyData
- print("Stored key in memory only (no keychain persistence)")
+ try openSession(unlockKey: keyData)
+ print("Opened session in memory only (no keychain persistence)")
}
- /// Clear the encryption key from memory.
- /// This forces getEncryptionKey() to fetch from keychain on next access.
+ /// Clear the unlock key from memory.
+ /// This forces getEncryptionKey() to fetch the unlock key from keychain on next access.
public func clearEncryptionKeyFromMemory() {
- self.encryptionKey = nil
+ self.unlockKey = nil
clearLastSuccessfulAuth()
- print("Cleared encryption key from memory")
+ print("Cleared unlock key from memory")
}
- /// Store the encryption key in memory AND persist to keychain if Face ID is enabled.
- public func storeEncryptionKey(base64Key: String) throws {
- // First store in memory
- try storeEncryptionKeyInMemory(base64Key: base64Key)
+ /// Open a session in memory with the unlock key (the password-derived KEK) AND persist that key to keychain
+ /// if Face ID is enabled.
+ public func storeUnlockKey(base64Key: String) throws {
+ // First open the session in memory
+ try storeUnlockKeyInMemory(base64Key: base64Key)
// Then persist to keychain if Face ID is enabled AND keystore is available
- if self.enabledAuthMethods.contains(.faceID), let keyData = self.encryptionKey {
+ if self.enabledAuthMethods.contains(.faceID), let keyData = self.unlockKey {
if isKeystoreAvailable() {
try storeKeyInKeychain(keyData)
- print("Stored key in memory and persisted to keychain")
+ print("Opened session and persisted unlock key to keychain")
} else {
- print("Stored key in memory (keystore unavailable - device passcode not set, skipping keychain)")
+ print("Opened session in memory (keystore unavailable - device passcode not set, skipping keychain)")
}
} else {
- print("Stored key in memory (Face ID not enabled, skipping keychain)")
+ print("Opened session in memory (Face ID not enabled, skipping keychain)")
+ }
+ }
+
+ /*
+ * The unlock key (the password-derived KEK) is the one secret a session holds; keychain and PIN only protect
+ * that same key. It opens the cached account key chain as the server returned it: KEK > Account Key > vault
+ * key and account private key, which are derived on demand and never stored. A legacy account has no chain
+ * and its KEK is the vault key.
+ */
+
+ /// Open a session with the unlock key, after checking that it opens the cached account key chain.
+ internal func openSession(unlockKey: Data) throws {
+ guard unlockKey.count == 32 else {
+ throw NSError(domain: "VaultStore", code: 7, userInfo: [NSLocalizedDescriptionKey: "Invalid key length. Expected 32 bytes"])
}
+
+ _ = try openAccountKeyChain(with: unlockKey)
+ self.unlockKey = unlockKey
}
/// Store the key derivation parameters used for deriving the encryption key from the plain text password
- public func storeEncryptionKeyDerivationParams(_ keyDerivationParams: String) throws {
+ public func storeUnlockKeyDerivationParams(_ keyDerivationParams: String) throws {
// Store the key derivation params in memory
self.keyDerivationParams = keyDerivationParams
// Store the key derivation params in UserDefaults
- self.userDefaults.set(keyDerivationParams, forKey: VaultConstants.encryptionKeyDerivationParamsKey)
+ self.userDefaults.set(keyDerivationParams, forKey: VaultConstants.unlockKeyDerivationParamsKey)
print("Stored key derivation params in UserDefaults")
}
/// Get the key derivation parameters used for deriving the encryption key from the plain text password
- public func getEncryptionKeyDerivationParams() -> String? {
+ public func getUnlockKeyDerivationParams() -> String? {
return self.keyDerivationParams
}
@@ -95,21 +109,13 @@ extension VaultStore {
return self.userDefaults.string(forKey: VaultConstants.accountKeyChainKey)
}
- /// The vault key an unlock method (PIN) stored, as base64.
- public func resolveStoredUnlockKey(base64Key: String) -> String {
- guard let key = Data(base64Encoded: base64Key), let vaultKey = try? resolveVaultEncryptionKey(derivedKey: key) else {
- return base64Key
- }
- return vaultKey.base64EncodedString()
- }
-
- /// Turn a password-derived key (KEK) into the vault encryption key.
- internal func resolveVaultEncryptionKey(derivedKey: Data) throws -> Data {
+ /// Open the cached account key chain with the KEK. Without a chain (legacy account) the KEK is the vault key.
+ internal func openAccountKeyChain(with derivedKey: Data) throws -> (vaultEncryptionKey: Data, accountPrivateKey: String?) {
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 derivedKey
+ return (derivedKey, nil)
}
guard let encryptedVek = chain["encryptedVek"] as? String, !encryptedVek.isEmpty else {
@@ -117,7 +123,14 @@ extension VaultStore {
}
let accountKey = try unwrapKey(encryptedAccountKey, with: derivedKey)
- return try unwrapKey(encryptedVek, with: accountKey)
+ let vaultEncryptionKey = try unwrapKey(encryptedVek, with: accountKey)
+
+ // A private key that does not open must not fail the unlock; grants stay closed until the next login.
+ var accountPrivateKey: String?
+ if let encryptedPrivateKey = chain["encryptedAccountPrivateKey"] as? String, !encryptedPrivateKey.isEmpty, let privateKey = try? unwrapKey(encryptedPrivateKey, with: accountKey) {
+ accountPrivateKey = String(data: privateKey, encoding: .utf8)
+ }
+ return (vaultEncryptionKey, accountPrivateKey)
}
/// Decrypt a wrapped key with the given key.
@@ -130,11 +143,11 @@ extension VaultStore {
return try AES.GCM.open(sealedBox, using: SymmetricKey(data: key))
}
- /// Verify the password and return the vault encryption key if correct.
+ /// Verify the password and return the unlock key (the password-derived KEK, base64) if correct.
public func verifyPassword(_ password: String) -> String? {
do {
// Get encryption key derivation parameters
- guard let paramsString = getEncryptionKeyDerivationParams(),
+ guard let paramsString = getUnlockKeyDerivationParams(),
let paramsData = paramsString.data(using: .utf8),
let params = try? JSONSerialization.jsonObject(with: paramsData) as? [String: Any],
let salt = params["salt"] as? String,
@@ -145,7 +158,7 @@ extension VaultStore {
// Derive the KEK from the password and unwrap the chain; a wrong password fails the unwrap.
let derivedKey = try deriveKeyFromPassword(password, salt: salt, encryptionType: encryptionType, encryptionSettings: encryptionSettings)
- let vaultKey = try resolveVaultEncryptionKey(derivedKey: derivedKey)
+ let vaultEncryptionKey = try openAccountKeyChain(with: derivedKey).vaultEncryptionKey
// Try to decrypt the vault to verify the password is correct
guard let encryptedDbBase64 = getEncryptedDatabase(),
@@ -154,12 +167,12 @@ extension VaultStore {
}
// Test decryption
- let key = SymmetricKey(data: vaultKey)
+ let key = SymmetricKey(data: vaultEncryptionKey)
let sealedBox = try AES.GCM.SealedBox(combined: encryptedDbData)
_ = try AES.GCM.open(sealedBox, using: key)
- // If decryption succeeded, return the vault key as base64
- return vaultKey.base64EncodedString()
+ // If decryption succeeded, return the unlock key as base64
+ return derivedKey.base64EncodedString()
} catch {
// Password incorrect or decryption failed
return nil
@@ -185,7 +198,7 @@ extension VaultStore {
let decryptedData = try AES.GCM.open(sealedBox, using: key)
/*
- * If the decryption succeeds, try to persist the used encryption key in the keychain.
+ * If the decryption succeeds, try to persist the unlock key of this session 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.
@@ -193,9 +206,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() {
+ if self.enabledAuthMethods.contains(.faceID) && isKeystoreAvailable(), let unlockKey = self.unlockKey {
do {
- try storeKeyInKeychain(encryptionKey)
+ try storeKeyInKeychain(unlockKey)
} 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
@@ -242,12 +255,24 @@ extension VaultStore {
/// Get the encryption key - the key used to encrypt and decrypt the vault.
internal func getEncryptionKey() throws -> Data {
- // If key is already in memory, return it immediately
- // This is the common case during normal operation
- if let key = self.encryptionKey {
+ return try openAccountKeyChain(with: try getUnlockKey()).vaultEncryptionKey
+ }
+
+ /// Get the unlock key - the password-derived KEK the keychain and PIN protect.
+ internal func getUnlockKey() throws -> Data {
+ if let key = self.unlockKey {
return key
}
+ try openSessionFromKeychain()
+ guard let key = self.unlockKey else {
+ throw AppError.keystoreKeyNotFound
+ }
+ return key
+ }
+
+ /// Open a session with the unlock 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
if self.enabledAuthMethods.contains(.faceID) && isKeystoreAvailable() {
@@ -277,15 +302,22 @@ extension VaultStore {
#endif
print("Attempting to get encryption key from keychain as Face ID is enabled and keystore is available")
+ let keyData: Data
do {
- let keyData = try retrieveKeyFromKeychain(context: context)
- self.encryptionKey = keyData
- return keyData
+ keyData = try retrieveKeyFromKeychain(context: context)
} catch let vaultError as AppError {
throw vaultError
} catch {
throw AppError.keystoreKeyNotFound
}
+
+ do {
+ try openSession(unlockKey: keyData)
+ } catch {
+ print("The unlock key from the keychain does not open the account key chain: \(error)")
+ throw AppError.vaultDecryptFailed
+ }
+ return
}
// Key not in memory and cannot retrieve from keychain
@@ -333,7 +365,7 @@ extension VaultStore {
return status == errSecSuccess
}
- /// Store the encryption key in the keychain
+ /// Store the unlock key in the keychain
internal func storeKeyInKeychain(_ keyData: Data) throws {
// Check if keystore is available (device passcode must be set)
guard isKeystoreAvailable() else {
@@ -355,7 +387,7 @@ extension VaultStore {
let query: [String: Any] = [
kSecClass as String: kSecClassGenericPassword,
kSecAttrService as String: VaultConstants.keychainService,
- kSecAttrAccount as String: VaultConstants.encryptionKeyKey,
+ kSecAttrAccount as String: VaultConstants.unlockKeyKey,
kSecAttrAccessGroup as String: VaultConstants.keychainAccessGroup,
kSecValueData as String: keyData,
kSecAttrAccessControl as String: accessControl
@@ -374,7 +406,7 @@ extension VaultStore {
let query: [String: Any] = [
kSecClass as String: kSecClassGenericPassword,
kSecAttrService as String: VaultConstants.keychainService,
- kSecAttrAccount as String: VaultConstants.encryptionKeyKey,
+ kSecAttrAccount as String: VaultConstants.unlockKeyKey,
kSecAttrAccessGroup as String: VaultConstants.keychainAccessGroup
]
@@ -386,7 +418,7 @@ extension VaultStore {
// MARK: - Private Keychain Methods
- /// Retrieve the encryption key from the keychain
+ /// Retrieve the unlock key from the keychain
private func retrieveKeyFromKeychain(context: LAContext) throws -> Data {
// Ensure interaction is allowed so system can prompt for biometric authentication
context.interactionNotAllowed = false
@@ -399,7 +431,7 @@ extension VaultStore {
let query: [String: Any] = [
kSecClass as String: kSecClassGenericPassword,
kSecAttrService as String: VaultConstants.keychainService,
- kSecAttrAccount as String: VaultConstants.encryptionKeyKey,
+ kSecAttrAccount as String: VaultConstants.unlockKeyKey,
kSecAttrAccessGroup as String: VaultConstants.keychainAccessGroup,
kSecReturnData as String: true,
kSecUseAuthenticationContext as String: context,
diff --git a/apps/mobile-app/ios/VaultStoreKit/VaultStore+Pin.swift b/apps/mobile-app/ios/VaultStoreKit/VaultStore+Pin.swift
index 9f9879f74..ae70be105 100644
--- a/apps/mobile-app/ios/VaultStoreKit/VaultStore+Pin.swift
+++ b/apps/mobile-app/ios/VaultStoreKit/VaultStore+Pin.swift
@@ -53,8 +53,8 @@ extension VaultStore {
throw AppError.biometricNotAvailable
}
- // Get vault encryption key from memory (vault must be unlocked)
- let vaultEncryptionKey = try getEncryptionKey()
+ // Get the unlock key from memory (vault must be unlocked): the PIN protects the KEK, never the vault key
+ let unlockKey = try getUnlockKey()
// Generate random salt
var salt = Data(count: 16)
@@ -68,9 +68,9 @@ extension VaultStore {
// Derive key from PIN + salt using Argon2id
let pinKey = try derivePinKey(pin: pin, salt: salt)
- // Encrypt the vault encryption key using AES-GCM
+ // Encrypt the unlock key using AES-GCM
let symmetricKey = SymmetricKey(data: pinKey)
- let sealedBox = try AES.GCM.seal(vaultEncryptionKey, using: symmetricKey)
+ let sealedBox = try AES.GCM.seal(unlockKey, using: symmetricKey)
guard let encryptedData = sealedBox.combined else {
throw NSError(domain: "VaultStore", code: 23, userInfo: [NSLocalizedDescriptionKey: "Failed to encrypt vault key"])
}
@@ -92,10 +92,10 @@ extension VaultStore {
// MARK: - PIN Unlock Methods
/// Unlock with PIN
- /// Returns the decrypted vault encryption key
+ /// Returns the decrypted unlock key (the password-derived KEK)
///
/// - Parameter pin: The PIN to use for unlocking
- /// - Returns: The decrypted vault encryption key (base64)
+ /// - Returns: The decrypted unlock key (base64), to open the session with
/// - Throws: PinUnlockError with specific error type and metadata
public func unlockWithPin(_ pin: String) throws -> String {
do {
@@ -114,8 +114,8 @@ extension VaultStore {
try storePinFailedAttemptsInKeychain(0)
markSuccessfulAuth()
- // Return the decrypted vault encryption key as base64.
- return resolveStoredUnlockKey(base64Key: decryptedKey.base64EncodedString())
+ // Return the decrypted unlock key as base64.
+ return decryptedKey.base64EncodedString()
} catch {
// Increment failed attempts
let currentAttempts = getPinFailedAttempts()
diff --git a/apps/mobile-app/ios/VaultStoreKit/VaultStore+PublicKeyCrypto.swift b/apps/mobile-app/ios/VaultStoreKit/VaultStore+PublicKeyCrypto.swift
index 04823cbda..773853b83 100644
--- a/apps/mobile-app/ios/VaultStoreKit/VaultStore+PublicKeyCrypto.swift
+++ b/apps/mobile-app/ios/VaultStoreKit/VaultStore+PublicKeyCrypto.swift
@@ -3,17 +3,17 @@ import Security
/// Extension for the VaultStore class to handle RSA public key encryption
extension VaultStore {
- /// Encrypts the vault's encryption key using an RSA public key for mobile login
- /// This method gets the internal encryption key and encrypts it with the provided public key
+ /// Encrypts the unlock key (the password-derived KEK) 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 encryption key
+ /// - Returns: The encrypted unlock key
public func encryptDecryptionKeyForMobileLogin(publicKeyJWK: String) throws -> Data {
- // Get the current encryption key from the vault store
- // This will only work if the vault is unlocked (encryption key is in memory)
- let encryptionKey = try getEncryptionKey()
+ // 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 encryption key with the provided public key
- return try encryptWithPublicKey(data: encryptionKey, publicKeyJWK: publicKeyJWK)
+ // Encrypt the unlock key with the provided public key
+ return try encryptWithPublicKey(data: unlockKey, publicKeyJWK: publicKeyJWK)
}
/// Encrypts data using an RSA public key
diff --git a/apps/mobile-app/ios/VaultStoreKit/VaultStore+Sync.swift b/apps/mobile-app/ios/VaultStoreKit/VaultStore+Sync.swift
index 242e89583..2d76370a7 100644
--- a/apps/mobile-app/ios/VaultStoreKit/VaultStore+Sync.swift
+++ b/apps/mobile-app/ios/VaultStoreKit/VaultStore+Sync.swift
@@ -34,14 +34,6 @@ extension VaultStore {
try await sync.mutateVault(using: webApiService)
}
- /// Adopt the session key the engine reports, unless it is the key already in memory.
- public func adoptEncryptionKey(base64Key: String) throws {
- if let current = encryptionKey, current == Data(base64Encoded: base64Key) {
- return
- }
- try storeEncryptionKey(base64Key: base64Key)
- }
-
/// The logs of the recent sync engine runs as JSON text, newest first, for the developer tools.
public func getVaultSyncLogs() -> String {
return VaultSyncRunLog.persistedLogs(in: userDefaults)
diff --git a/apps/mobile-app/ios/VaultStoreKit/VaultStore.swift b/apps/mobile-app/ios/VaultStoreKit/VaultStore.swift
index 1d9949833..d0c5520ac 100644
--- a/apps/mobile-app/ios/VaultStoreKit/VaultStore.swift
+++ b/apps/mobile-app/ios/VaultStoreKit/VaultStore.swift
@@ -32,11 +32,27 @@ public class VaultStore {
/// The live vault, held in the Rust core's memory. Nil while vault is locked.
internal var dbConnection: SqliteMemoryDatabase?
- /// The encryption key for the vault.
- internal var encryptionKey: Data?
+ /// The unlock key: the password-derived KEK. 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 private key (JWK) of the unlocked session.
- internal var accountPrivateKey: String?
+ /// The encryption key for the vault, derived from the unlock 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.
+ internal var accountPrivateKey: String? {
+ return sessionKeys?.accountPrivateKey
+ }
+
+ /// What the unlock key opens in the cached account key chain.
+ private var sessionKeys: (vaultEncryptionKey: Data, accountPrivateKey: String?)? {
+ guard let unlockKey = unlockKey else {
+ return nil
+ }
+ return try? openAccountKeyChain(with: unlockKey)
+ }
/// Last successful biometric/PIN auth operation.
private var lastSuccessfulAuthAt: TimeInterval?
@@ -71,7 +87,7 @@ public class VaultStore {
/// Whether the vault is currently unlocked
public var isVaultUnlocked: Bool {
- return encryptionKey != nil
+ return unlockKey != nil
}
// MARK: - Authentication Recency
@@ -128,7 +144,7 @@ public class VaultStore {
self.autoLockTimeout = userDefaults.integer(forKey: VaultConstants.autoLockTimeoutKey)
}
- if let savedParams = userDefaults.string(forKey: VaultConstants.encryptionKeyDerivationParamsKey) {
+ if let savedParams = userDefaults.string(forKey: VaultConstants.unlockKeyDerivationParamsKey) {
self.keyDerivationParams = savedParams
}
}
diff --git a/apps/mobile-app/ios/VaultStoreKitTests/VaultStoreKitTests.swift b/apps/mobile-app/ios/VaultStoreKitTests/VaultStoreKitTests.swift
index 8a10f9ebd..6a626a5ea 100644
--- a/apps/mobile-app/ios/VaultStoreKitTests/VaultStoreKitTests.swift
+++ b/apps/mobile-app/ios/VaultStoreKitTests/VaultStoreKitTests.swift
@@ -3,14 +3,14 @@ import XCTest
final public class VaultStoreKitTests: XCTestCase {
var vaultStore: VaultStore!
- let testEncryptionKeyBase64 = "/9So3C83JLDIfjsF0VQOc4rz1uAFtIseW7yrUuztAD0=" // 32 bytes for AES-256
+ let testUnlockKeyBase64 = "/9So3C83JLDIfjsF0VQOc4rz1uAFtIseW7yrUuztAD0=" // 32 bytes for AES-256
override public func setUp() {
super.setUp()
vaultStore = VaultStore.shared
do {
- try vaultStore.storeEncryptionKey(base64Key: testEncryptionKeyBase64)
+ try vaultStore.storeUnlockKey(base64Key: testUnlockKeyBase64)
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.swift
index 935b18dc7..f547f29bf 100644
--- a/apps/mobile-app/ios/VaultUtils/VaultConstants.swift
+++ b/apps/mobile-app/ios/VaultUtils/VaultConstants.swift
@@ -8,11 +8,11 @@ public struct VaultConstants {
public static let userDefaultsSuite = "group.net.aliasvault.autofill"
public static let vaultMetadataKey = "aliasvault_vault_metadata"
- public static let encryptionKeyKey = "aliasvault_encryption_key"
+ public static let unlockKeyKey = "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"
- public static let encryptionKeyDerivationParamsKey = "aliasvault_encryption_key_derivation_params"
+ public static let unlockKeyDerivationParamsKey = "aliasvault_encryption_key_derivation_params"
public static let accountKeyChainKey = "aliasvault_account_key_chain"
public static let usernameKey = "aliasvault_username"
public static let offlineModeKey = "aliasvault_offline_mode"
diff --git a/apps/mobile-app/specs/NativeVaultManager.ts b/apps/mobile-app/specs/NativeVaultManager.ts
index ad2921231..e2a1d6202 100644
--- a/apps/mobile-app/specs/NativeVaultManager.ts
+++ b/apps/mobile-app/specs/NativeVaultManager.ts
@@ -64,11 +64,11 @@ export interface Spec extends TurboModule {
// Database/encryption key operations
storeMetadata(metadata: string): Promise<void>;
setAuthMethods(authMethods: string[]): Promise<void>;
- storeEncryptionKeyInMemory(base64EncryptionKey: string): Promise<void>;
+ storeUnlockKeyInMemory(base64UnlockKey: string): Promise<void>;
clearEncryptionKeyFromMemory(): Promise<void>;
- storeEncryptionKey(base64EncryptionKey: string): Promise<void>;
- storeEncryptionKeyDerivationParams(keyDerivationParams: string): Promise<void>;
- getEncryptionKeyDerivationParams(): Promise<string | null>;
+ storeUnlockKey(base64UnlockKey: string): Promise<void>;
+ storeUnlockKeyDerivationParams(keyDerivationParams: string): Promise<void>;
+ getUnlockKeyDerivationParams(): Promise<string | null>;
storeAccountKeyChain(chainJson: string | null): Promise<void>;
getAccountKeyChain(): Promise<string | null>;
resolveVaultKey(base64DerivedKey: string): Promise<string>;
diff --git a/apps/mobile-app/utils/SqliteClient.ts b/apps/mobile-app/utils/SqliteClient.ts
index 3abf25537..ce6298809 100644
--- a/apps/mobile-app/utils/SqliteClient.ts
+++ b/apps/mobile-app/utils/SqliteClient.ts
@@ -1,4 +1,4 @@
-import type { EncryptionKeyDerivationParams, VaultMetadata } from '@aliasvault/models/metadata';
+import type { UnlockKeyDerivationParams, VaultMetadata } from '@aliasvault/models/metadata';
import { asyncRepository } from '@aliasvault/client/database/DbOp';
import { EncryptionKeyRepository } from '@aliasvault/client/database/repositories/EncryptionKeyRepository';
import { FolderRepository } from '@aliasvault/client/database/repositories/FolderRepository';
@@ -169,31 +169,31 @@ class SqliteClient {
}
/**
- * Store the encryption key in memory only (no keychain persistence).
+ * Open a session in memory with the unlock key (the password-derived KEK), without keychain persistence.
* Use this to test if a password-derived key is valid before persisting.
*
- * @param base64EncryptionKey The base64 encoded encryption key
+ * @param base64UnlockKey The base64 encoded unlock key
*/
- public async storeEncryptionKeyInMemory(base64EncryptionKey: string): Promise<void> {
+ public async storeUnlockKeyInMemory(base64UnlockKey: string): Promise<void> {
try {
- await NativeVaultManager.storeEncryptionKeyInMemory(base64EncryptionKey);
+ await NativeVaultManager.storeUnlockKeyInMemory(base64UnlockKey);
} catch (error) {
- console.error('Error storing encryption key in memory:', error);
+ console.error('Error storing unlock key in memory:', error);
throw error;
}
}
/**
- * Store the encryption key in memory AND persist to keychain (may trigger biometric prompt).
+ * Open a session with the unlock key (the password-derived KEK) AND persist it to keychain (may trigger biometric prompt).
*
- * @param base64EncryptionKey The base64 encoded encryption key
+ * @param base64UnlockKey The base64 encoded unlock key
*/
- public async storeEncryptionKey(base64EncryptionKey: string): Promise<void> {
+ public async storeUnlockKey(base64UnlockKey: string): Promise<void> {
try {
- // Store the encryption key in the native module
- await NativeVaultManager.storeEncryptionKey(base64EncryptionKey);
+ // Open the session with the unlock key in the native module
+ await NativeVaultManager.storeUnlockKey(base64UnlockKey);
} catch (error) {
- console.error('Error storing encryption key:', error);
+ console.error('Error storing unlock key:', error);
throw error;
}
}
@@ -203,10 +203,10 @@ class SqliteClient {
*
* @param keyDerivationParams The key derivation parameters
*/
- public async storeEncryptionKeyDerivationParams(keyDerivationParams: EncryptionKeyDerivationParams): Promise<void> {
+ public async storeUnlockKeyDerivationParams(keyDerivationParams: UnlockKeyDerivationParams): Promise<void> {
try {
const keyDerivationParamsJson = JSON.stringify(keyDerivationParams);
- await NativeVaultManager.storeEncryptionKeyDerivationParams(keyDerivationParamsJson);
+ await NativeVaultManager.storeUnlockKeyDerivationParams(keyDerivationParamsJson);
} catch (error) {
console.error('Error storing encryption key derivation params:', error);
throw error;
diff --git a/core/client/src/auth/MasterPasswordService.ts b/core/client/src/auth/MasterPasswordService.ts
index 5269ec8ea..ec05ef317 100644
--- a/core/client/src/auth/MasterPasswordService.ts
+++ b/core/client/src/auth/MasterPasswordService.ts
@@ -8,7 +8,7 @@ import { SrpAuthService, type SrpClientProof } from './SrpAuthService';
import { VaultKeyService } from './VaultKeyService';
import type { WebApiService } from '../api/WebApiService';
-import type { EncryptionKeyDerivationParams } from '@aliasvault/models/metadata';
+import type { UnlockKeyDerivationParams } from '@aliasvault/models/metadata';
import type { PasswordChangeInitiateResponse, PasswordChangeRequest } from '@aliasvault/models/webapi';
/**
@@ -66,8 +66,8 @@ export class MasterPasswordService {
/**
* The derivation parameters of the password this device holds, or null before the first online unlock.
*/
- public static async getStoredDerivationParams(): Promise<EncryptionKeyDerivationParams | null> {
- return getPlatform().storage.get<EncryptionKeyDerivationParams>(StorageKeys.ENCRYPTION_KEY_DERIVATION_PARAMS);
+ public static async getStoredDerivationParams(): Promise<UnlockKeyDerivationParams | null> {
+ return getPlatform().storage.get<UnlockKeyDerivationParams>(StorageKeys.UNLOCK_KEY_DERIVATION_PARAMS);
}
/**
@@ -88,7 +88,7 @@ export class MasterPasswordService {
const prepared = await SrpAuthService.prepareCredentials(password, parameters.salt, parameters.encryptionSettings);
try {
- await VaultKeyService.resolveEncryptionKeyOffline(prepared.passwordHashBase64);
+ await VaultKeyService.verifyUnlockKey(prepared.passwordHashBase64);
return PasswordVerificationResult.Success;
} catch (error) {
const code = error instanceof Error ? extractErrorCode(error.message) : null;
@@ -193,7 +193,7 @@ export class MasterPasswordService {
}, false);
// Persist the new Account Key and its derivation parameters.
- await VaultKeyService.persistNewAccountKey(newEncryptedAccountKey, { salt: next.salt, encryptionType: next.encryptionType, encryptionSettings: next.encryptionSettings });
+ await VaultKeyService.persistNewAccountKey(newEncryptedAccountKey, { salt: next.salt, encryptionType: next.encryptionType, encryptionSettings: next.encryptionSettings }, next.kekBase64);
}
/**
diff --git a/core/client/src/auth/VaultKeyService.ts b/core/client/src/auth/VaultKeyService.ts
index 64abd27e3..72fe4142b 100644
--- a/core/client/src/auth/VaultKeyService.ts
+++ b/core/client/src/auth/VaultKeyService.ts
@@ -11,7 +11,7 @@ import { StorageKeys } from '../constants/StorageKeys';
import { EncryptionUtility } from '../crypto/EncryptionUtility';
import { getPlatform } from '../platform/ClientPlatform';
-import type { EncryptionKeyDerivationParams } from '@aliasvault/models/metadata';
+import type { UnlockKeyDerivationParams } from '@aliasvault/models/metadata';
/**
* Result of fetching the vault key from the server.
@@ -22,7 +22,17 @@ export type FetchVaultKeyResult = {
};
/**
- * Static helper for fetching, decrypting, and caching the account-key unlock chain (KEK → AK → VEK + account keypair).
+ * The keys an unlock key opens.
+ */
+export type SessionKeys = {
+ /** The vault encryption key (VEK). */
+ vaultEncryptionKey: string;
+ /** The account private key (JWK). */
+ accountPrivateKey: string | null;
+};
+
+/**
+ * Static helper for fetching, caching and opening the account-key unlock chain (KEK → AK → VEK + account keypair).
*/
export class VaultKeyService {
/**
@@ -45,61 +55,69 @@ export class VaultKeyService {
}
/**
- * Resolve the vault encryption key right after authentication: fetch the vault key from the server, decrypt
- * the Account Key with the password-derived key (KEK), and with the AK decrypt the VEK and the account
- * private key. All encrypted blobs are cached for offline unlock. For legacy users (server explicitly
- * reports no vault key) the derived key itself is the encryption key and any stale cached chain is cleared.
+ * Right after authentication: fetch the account's key chain from the server, check that the unlock key opens it
+ * and cache it for offline unlock.
+ * @param unlockKeyBase64 - the password-derived key (the KEK)
+ * @param webApi - the API client to use
+ * @throws Error with {@link AppErrorCode.VAULT_DECRYPT_FAILED} when the key does not open the chain (wrong password).
*/
- public static async resolveEncryptionKey(derivedKeyBase64: string, webApi?: WebApiService): Promise<string> {
+ public static async refreshKeyChain(unlockKeyBase64: string, webApi?: WebApiService): Promise<void> {
const result = await VaultKeyService.fetchVaultKey(webApi);
if (!result.supported) {
- // Older server: trust the local cache. Legacy accounts have no cached blob chain and use the derived key.
- return VaultKeyService.resolveFromLocalCache(derivedKeyBase64);
+ // Older server: trust the local cache.
+ await VaultKeyService.verifyUnlockKey(unlockKeyBase64);
+ return;
}
if (!result.vaultKey) {
await getPlatform().storage.removeMany([StorageKeys.ENCRYPTED_VEK, StorageKeys.ENCRYPTED_ACCOUNT_KEY, StorageKeys.ACCOUNT_PUBLIC_KEY, StorageKeys.ENCRYPTED_ACCOUNT_PRIVATE_KEY]);
- return derivedKeyBase64;
+ return;
}
- const vek = await VaultKeyService.decryptKeyChainOrThrow(result.vaultKey, derivedKeyBase64);
+ await VaultKeyService.openChain(unlockKeyBase64, result.vaultKey.encryptedAccountKey, result.vaultKey.encryptedVek ?? null, null);
await VaultKeyService.cacheVaultKeyBlobs(result.vaultKey);
- return vek;
}
/**
- * Resolve the vault encryption key offline: decrypt the locally cached blob chain with the derived key. For
- * legacy users (no cached chain) the derived key itself is returned.
- * @param derivedKeyBase64 - the password-derived key
- * @throws Error with {@link AppErrorCode.VAULT_DECRYPT_FAILED} when decryption fails (wrong password).
+ * Check offline that the unlock key opens the locally cached chain. A legacy account has no chain to check against.
+ * @param unlockKeyBase64 - the password-derived key (the KEK), typed in or restored by PIN
+ * @throws Error with {@link AppErrorCode.VAULT_DECRYPT_FAILED} when the key does not open the chain (wrong password).
*/
- public static async resolveEncryptionKeyOffline(derivedKeyBase64: string): Promise<string> {
- return VaultKeyService.resolveFromLocalCache(derivedKeyBase64);
+ public static async verifyUnlockKey(unlockKeyBase64: string): Promise<void> {
+ await VaultKeyService.openKeyChain(unlockKeyBase64);
}
/**
- * Whether this device holds a vault key, i.e. whether the session encryption key is a VEK rather than the raw
- * password-derived key. This is the local source of truth for "am I on the account-key model": the cache is
- * written by {@link resolveEncryptionKey} on every login and cleared when the server reports no vault key, so
- * it needs no server round-trip. A false answer is only ever stale in one direction (another device migrated
- * since the last login), which the background sync resolves by adopting the remote key before any vault work happens.
+ * Whether this device holds a key chain, i.e. whether the account is on the account-key model rather than a
+ * legacy account whose unlock key encrypts the vault directly. The cache is written on every login and cleared
+ * when the server reports no vault key, so it needs no server round-trip. A false answer is only ever stale in
+ * one direction (another device migrated since the last login), which the sync resolves by adopting the remote chain.
*/
public static async hasLocalVaultKey(): Promise<boolean> {
return (await getPlatform().storage.get(StorageKeys.ENCRYPTED_ACCOUNT_KEY) as string | null) !== null;
}
/**
- * Refresh the local blob-chain cache from the server without needing the KEK.
- * @param webApi - the API client to use
+ * The unlock key of this session (the password-derived KEK), or null when the vault is locked.
*/
- public static async cacheEncryptedVekFromServer(webApi?: WebApiService): Promise<void> {
- const result = await VaultKeyService.fetchVaultKey(webApi);
- if (result.vaultKey) {
- await VaultKeyService.cacheVaultKeyBlobs(result.vaultKey);
- } else if (result.supported) {
- await getPlatform().storage.removeMany([StorageKeys.ENCRYPTED_VEK, StorageKeys.ENCRYPTED_ACCOUNT_KEY, StorageKeys.ACCOUNT_PUBLIC_KEY, StorageKeys.ENCRYPTED_ACCOUNT_PRIVATE_KEY]);
- }
+ public static async getSessionUnlockKey(): Promise<string | null> {
+ return (await getPlatform().storage.get(StorageKeys.UNLOCK_KEY)) as string | null;
+ }
+
+ /**
+ * The keys of the unlocked session, derived from the unlock key and the cached chain, or null when the vault is locked.
+ */
+ public static async getSessionKeys(): Promise<SessionKeys | null> {
+ const unlockKey = await VaultKeyService.getSessionUnlockKey();
+ return unlockKey ? VaultKeyService.openKeyChain(unlockKey) : null;
+ }
+
+ /**
+ * The vault encryption key of the unlocked session, or null when the vault is locked.
+ */
+ public static async getSessionVaultEncryptionKey(): Promise<string | null> {
+ return (await VaultKeyService.getSessionKeys())?.vaultEncryptionKey ?? null;
}
/**
@@ -107,7 +125,7 @@ export class VaultKeyService {
* the account has no keypair yet (legacy account, not migrated to manifest-v1 yet). Used to decrypt shared-manifest VEK grants.
*/
public static async getSessionAccountPrivateKey(): Promise<string | null> {
- return (await getPlatform().storage.get(StorageKeys.ACCOUNT_PRIVATE_KEY)) as string | null;
+ return (await VaultKeyService.getSessionKeys())?.accountPrivateKey ?? null;
}
/**
@@ -118,117 +136,62 @@ export class VaultKeyService {
}
/**
- * Persist the account-key blob chain produced client-side (registration is web-client-only, so this runs on
- * the account-key migration push) and stage the session private key.
- * @param blobs - the encrypted Account Key and KEK derivation parameters for the given unlock method.
- */
- public static async adoptLocalAccountKeys(blobs: { encryptedAccountKey: string; encryptedVek: string; accountPublicKey: string; encryptedAccountPrivateKey: string; accountPrivateKey: string }): Promise<void> {
- await getPlatform().storage.setMany([
- { key: StorageKeys.ENCRYPTED_ACCOUNT_KEY, value: blobs.encryptedAccountKey },
- { key: StorageKeys.ENCRYPTED_VEK, value: blobs.encryptedVek },
- { key: StorageKeys.ACCOUNT_PUBLIC_KEY, value: blobs.accountPublicKey },
- { key: StorageKeys.ENCRYPTED_ACCOUNT_PRIVATE_KEY, value: blobs.encryptedAccountPrivateKey },
- { key: StorageKeys.ACCOUNT_PRIVATE_KEY, value: blobs.accountPrivateKey },
- ]);
- }
-
- /**
- * Persist new account key after a local password change.
+ * Persist new account key after a local password change. The session moves onto the new unlock key with it.
* @param newEncryptedAccountKey - the Account Key encrypted with the new password-derived KEK
* @param derivationParams - the KEK derivation parameters of the new password
+ * @param newUnlockKeyBase64 - the new password-derived KEK
*/
- public static async persistNewAccountKey(newEncryptedAccountKey: string, derivationParams: EncryptionKeyDerivationParams): Promise<void> {
+ public static async persistNewAccountKey(newEncryptedAccountKey: string, derivationParams: UnlockKeyDerivationParams, newUnlockKeyBase64: string): Promise<void> {
await getPlatform().storage.setMany([
{ key: StorageKeys.ENCRYPTED_ACCOUNT_KEY, value: newEncryptedAccountKey },
- { key: StorageKeys.ENCRYPTION_KEY_DERIVATION_PARAMS, value: derivationParams },
+ { key: StorageKeys.UNLOCK_KEY_DERIVATION_PARAMS, value: derivationParams },
+ { key: StorageKeys.UNLOCK_KEY, value: newUnlockKeyBase64 },
]);
}
/**
- * Resolve the key to actually use for a local additional unlock method (PIN, mobile QR), upgrading a pre-migration
- * stored key (the old KEK) to the VEK when needed.
- * @param storedKey - the key restored from the auxiliary unlock method
- * @param onUpgraded - optional callback invoked with the upgraded VEK when the stored key was the old KEK
+ * Open the locally cached chain with the unlock key. Without a cached chain (legacy account) the unlock key is
+ * the vault encryption key.
+ * @param unlockKeyBase64 - the password-derived key (the KEK)
+ * @throws Error with {@link AppErrorCode.VAULT_DECRYPT_FAILED} when the key does not open the chain.
*/
- public static async resolveStoredUnlockKey(storedKey: string, onUpgraded?: (vek: string) => Promise<void>): Promise<string> {
- const { key, upgraded } = await VaultKeyService.upgradeStoredKeyIfNeeded(storedKey);
- if (upgraded && onUpgraded) {
- await onUpgraded(key);
- }
- return key;
- }
-
- /**
- * Given a key restored from an auxiliary unlock method (PIN, mobile QR), return the key to actually use and
- * whether it was upgraded: a stored key that decrypts the cached chain was the old KEK, and the chain's VEK
- * supersedes it.
- * @param storedKey - the key restored from the auxiliary unlock method
- */
- private static async upgradeStoredKeyIfNeeded(storedKey: string): Promise<{ key: string; upgraded: boolean }> {
- try {
- const resolvedKey = await VaultKeyService.resolveFromLocalCache(storedKey);
- if (resolvedKey !== storedKey) {
- return { key: resolvedKey, upgraded: true };
- }
- return { key: storedKey, upgraded: false };
- } catch {
- return { key: storedKey, upgraded: false };
+ public static async openKeyChain(unlockKeyBase64: string): Promise<SessionKeys> {
+ const storage = getPlatform().storage;
+ const [encryptedAccountKey, encryptedVek, encryptedAccountPrivateKey] = await Promise.all([
+ storage.get<string>(StorageKeys.ENCRYPTED_ACCOUNT_KEY),
+ storage.get<string>(StorageKeys.ENCRYPTED_VEK),
+ storage.get<string>(StorageKeys.ENCRYPTED_ACCOUNT_PRIVATE_KEY),
+ ]);
+ if (!encryptedAccountKey) {
+ return { vaultEncryptionKey: unlockKeyBase64, accountPrivateKey: null };
}
+ return VaultKeyService.openChain(unlockKeyBase64, encryptedAccountKey, encryptedVek, encryptedAccountPrivateKey);
}
/**
- * Decrypt the locally cached blob chain with the given KEK, staging the session private key when the chain
- * carries one. Falls back to the derived key itself when nothing is cached (legacy account).
- * @param derivedKeyBase64 - the password-derived key (the KEK)
+ * Walk a chain: the unlock key decrypts the Account Key, which decrypts the VEK and the account private key.
+ * @param unlockKeyBase64 - the password-derived key (the KEK)
+ * @param encryptedAccountKey - the Account Key encrypted with the KEK
+ * @param encryptedVek - the VEK encrypted with the Account Key
+ * @param encryptedAccountPrivateKey - the account private key encrypted with the Account Key, or null when the account has none yet
*/
- private static async resolveFromLocalCache(derivedKeyBase64: string): Promise<string> {
- const encryptedAccountKey = (await getPlatform().storage.get(StorageKeys.ENCRYPTED_ACCOUNT_KEY)) as string | null;
- if (!encryptedAccountKey) {
- return derivedKeyBase64;
- }
-
- const encryptedVek = (await getPlatform().storage.get(StorageKeys.ENCRYPTED_VEK)) as string | null;
+ private static async openChain(unlockKeyBase64: string, encryptedAccountKey: string, encryptedVek: string | null, encryptedAccountPrivateKey: string | null): Promise<SessionKeys> {
if (!encryptedVek) {
- throw new Error('Cached vault key chain is missing the encrypted VEK');
+ throw new Error('Vault key chain is missing the encrypted VEK');
}
- const accountKey = await VaultKeyService.decryptKeyOrThrow(encryptedAccountKey, derivedKeyBase64);
- const vek = await VaultKeyService.decryptKeyOrThrow(encryptedVek, accountKey);
- await VaultKeyService.stageSessionPrivateKey(accountKey, (await getPlatform().storage.get(StorageKeys.ENCRYPTED_ACCOUNT_PRIVATE_KEY)) as string | null);
- return vek;
- }
-
- /**
- * Decrypt a fresh server response's chain with the KEK: AK first, then the VEK, staging the session private
- * key when the account has a keypair.
- * @param vaultKey - the server's vault key response
- * @param derivedKeyBase64 - the password-derived KEK
- */
- private static async decryptKeyChainOrThrow(vaultKey: VaultKeyResponse, derivedKeyBase64: string): Promise<string> {
- const accountKey = await VaultKeyService.decryptKeyOrThrow(vaultKey.encryptedAccountKey, derivedKeyBase64);
- const vek = await VaultKeyService.decryptKeyOrThrow(vaultKey.encryptedVek!, accountKey);
- await VaultKeyService.stageSessionPrivateKey(accountKey, vaultKey.encryptedAccountPrivateKey ?? null);
- return vek;
- }
+ const accountKey = await VaultKeyService.decryptKeyOrThrow(encryptedAccountKey, unlockKeyBase64);
+ const vaultEncryptionKey = await VaultKeyService.decryptKeyOrThrow(encryptedVek, accountKey);
- /**
- * Decrypt the account private key with the AK into session storage, so pull/grant flows can decrypt shared
- * VEKs. A chain without a keypair clears any stale session copy instead.
- * @param accountKeyBase64 - the encrypted Account Key
- * @param encryptedAccountPrivateKey - the account private key encrypted with the Account Key, or null when the account has none yet
- */
- private static async stageSessionPrivateKey(accountKeyBase64: string, encryptedAccountPrivateKey: string | null): Promise<void> {
- if (!encryptedAccountPrivateKey) {
- await getPlatform().storage.remove(StorageKeys.ACCOUNT_PRIVATE_KEY);
- return;
- }
- try {
- const privateKeyJwk = await EncryptionUtility.symmetricDecrypt(encryptedAccountPrivateKey, accountKeyBase64);
- await getPlatform().storage.set(StorageKeys.ACCOUNT_PRIVATE_KEY, privateKeyJwk);
- } catch {
- // A stale/corrupt private-key blob must not fail the unlock; grant decryption degrades until the next sync.
- await getPlatform().storage.remove(StorageKeys.ACCOUNT_PRIVATE_KEY);
+ let accountPrivateKey: string | null = null;
+ if (encryptedAccountPrivateKey) {
+ try {
+ accountPrivateKey = await EncryptionUtility.symmetricDecrypt(encryptedAccountPrivateKey, accountKey);
+ } catch {
+ // A stale/corrupt private-key blob must not fail the unlock; grant decryption degrades until the next login.
+ }
}
+ return { vaultEncryptionKey, accountPrivateKey };
}
/**
diff --git a/core/client/src/constants/StorageKeys.ts b/core/client/src/constants/StorageKeys.ts
index 8a449e437..e0b56a7b2 100644
--- a/core/client/src/constants/StorageKeys.ts
+++ b/core/client/src/constants/StorageKeys.ts
@@ -42,7 +42,7 @@ export const StorageKeys = {
/** 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. */
- ENCRYPTION_KEY_DERIVATION_PARAMS: 'local:encryptionKeyDerivationParams',
+ UNLOCK_KEY_DERIVATION_PARAMS: 'local:encryptionKeyDerivationParams',
/** The VEK encrypted with the Account Key, as returned by the server. */
ENCRYPTED_VEK: 'local:encryptedVek',
/** The Account Key encrypted with the password-derived KEK, as returned by the server. */
@@ -90,10 +90,11 @@ export const StorageKeys = {
* -- Session state (cleared when the vault locks) --
*/
- /** The decrypted vault encryption key. Session-only: it must never persist to disk. */
- ENCRYPTION_KEY: 'session:encryptionKey',
- /** The decrypted account private key (JWK). Session-only: it must never persist to disk. */
- ACCOUNT_PRIVATE_KEY: 'session:accountPrivateKey',
+ /**
+ * 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).
+ * Session-only: it must never persist to disk. An additional unlock method (PIN) protects this same key.
+ */
+ UNLOCK_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>;
@@ -112,10 +113,9 @@ export const AUTH_STORAGE_KEYS: readonly StorageKey[] = [
StorageKeys.CAPABILITIES,
];
-/** Keys that must not survive a vault lock: the decrypted keys. Hosts add anything they derive from decrypted data. */
+/** 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.ENCRYPTION_KEY,
- StorageKeys.ACCOUNT_PRIVATE_KEY,
+ StorageKeys.UNLOCK_KEY,
];
/**
@@ -138,7 +138,7 @@ export const vaultDataStorageKeys = (): StorageKey[] => [
StorageKeys.IS_DIRTY,
StorageKeys.MUTATION_SEQUENCE,
StorageKeys.IS_OFFLINE_MODE,
- StorageKeys.ENCRYPTION_KEY_DERIVATION_PARAMS,
+ StorageKeys.UNLOCK_KEY_DERIVATION_PARAMS,
StorageKeys.ENCRYPTED_VEK,
StorageKeys.ENCRYPTED_ACCOUNT_KEY,
StorageKeys.ACCOUNT_PUBLIC_KEY,
diff --git a/core/client/src/sharing/SharingService.ts b/core/client/src/sharing/SharingService.ts
index 1080ad5d5..7d81c20d4 100644
--- a/core/client/src/sharing/SharingService.ts
+++ b/core/client/src/sharing/SharingService.ts
@@ -264,7 +264,7 @@ export class SharingService {
* The session vault encryption key, or null while the vault is locked.
*/
private static async sessionEncryptionKey(): Promise<string | null> {
- return (await getPlatform().storage.get(StorageKeys.ENCRYPTION_KEY)) as string | null;
+ return VaultKeyService.getSessionVaultEncryptionKey();
}
/**
diff --git a/core/client/src/sync/VaultSync.ts b/core/client/src/sync/VaultSync.ts
index 50e4f863f..0aed0f729 100644
--- a/core/client/src/sync/VaultSync.ts
+++ b/core/client/src/sync/VaultSync.ts
@@ -12,6 +12,7 @@
import { CapabilityService } from '../api/CapabilityService';
import { AppErrorCode, extractErrorCode, isErrorCode } from '../api/errors/AppErrorCodes';
import { WebApiService } from '../api/WebApiService';
+import { VaultKeyService } from '../auth/VaultKeyService';
import { StorageKeys } from '../constants/StorageKeys';
import { getPlatform } from '../platform/ClientPlatform';
import { devError, devLog, devWarn } from '../platform/Logger';
@@ -109,11 +110,11 @@ export class VaultSync {
public async syncVaultWithServer(options: VaultSyncOptions = {}): Promise<FullVaultSyncResult> {
try {
const storage = getPlatform().storage;
- const [username, accessToken, encryptionKey] = await Promise.all([storage.get<string>(StorageKeys.USERNAME), storage.get<string>(StorageKeys.ACCESS_TOKEN), storage.get<string>(StorageKeys.ENCRYPTION_KEY)]);
+ const [username, accessToken, unlockKey] = await Promise.all([storage.get<string>(StorageKeys.USERNAME), storage.get<string>(StorageKeys.ACCESS_TOKEN), VaultKeyService.getSessionUnlockKey()]);
if (username === null || accessToken === null) {
return syncResult({ success: false });
}
- if (!encryptionKey) {
+ if (!unlockKey) {
return syncResult({ success: false, errorCode: AppErrorCode.VAULT_LOCKED });
}
@@ -142,17 +143,12 @@ export class VaultSync {
}
/**
- * Resolve the vault key right after login: open the account's key chain with the password-derived key (the cached
- * chain when the server cannot be reached) and store the VEK as the session key. A legacy account keeps the derived
- * key. Every sync assumes the key this stored.
- * @param derivedKeyBase64 - the password-derived key (KEK)
+ * Resolve the vault key right after login: the engine opens the account's key chain with the unlock key (the
+ * cached chain when the server cannot be reached) and caches it as-is.
+ * @param unlockKeyBase64 - the password-derived key (KEK)
*/
- public async resolveVaultKey(derivedKeyBase64: string): Promise<VaultSyncResolveVaultKeyResult> {
- const result = await this.run<VaultSyncResolveVaultKeyResult>('resolveVaultKey', {}, derivedKeyBase64);
- if (result.success && result.encryptionKey) {
- await getPlatform().storage.set(StorageKeys.ENCRYPTION_KEY, result.encryptionKey);
- }
- return result;
+ public async resolveVaultKey(unlockKeyBase64: string): Promise<VaultSyncResolveVaultKeyResult> {
+ return this.run<VaultSyncResolveVaultKeyResult>('resolveVaultKey', {}, unlockKeyBase64);
}
/**
@@ -176,8 +172,7 @@ export class VaultSync {
*/
public async migrateVaultManifest(): Promise<VaultManifestMigrationResult> {
try {
- const encryptionKey = await getPlatform().storage.get<string>(StorageKeys.ENCRYPTION_KEY);
- if (!encryptionKey) {
+ if (!await VaultKeyService.getSessionUnlockKey()) {
return { success: false, pushed: false, errorCode: AppErrorCode.VAULT_LOCKED };
}
if (await (await this.openVault()).requiresLegacySqliteBlobMigration()) {
@@ -199,7 +194,7 @@ export class VaultSync {
* Run one engine operation and adopt what it reported.
* @param operation - the operation
* @param options - what the caller asks beyond what the engine decides
- * @param encryptionKey - overrides the session key for the one operation that runs before it is known
+ * @param encryptionKey - the request key of the one operation that runs on the unlock key itself (resolveVaultKey)
*/
private async run<T extends VaultSyncEngineResultBase>(operation: VaultSyncOperation, options: VaultSyncOptions = {}, encryptionKey?: string): Promise<T> {
const request = await buildVaultSyncRequest(operation, options);
@@ -227,12 +222,6 @@ export class VaultSync {
if (result.isOfflineMode !== undefined) {
await storage.set(StorageKeys.IS_OFFLINE_MODE, result.isOfflineMode);
}
- if (result.sessionUpdates?.encryptionKey) {
- await storage.set(StorageKeys.ENCRYPTION_KEY, result.sessionUpdates.encryptionKey);
- }
- if (result.sessionUpdates?.accountPrivateKey) {
- await storage.set(StorageKeys.ACCOUNT_PRIVATE_KEY, result.sessionUpdates.accountPrivateKey);
- }
if (result.emailRouting) {
await storage.setMany([
{ key: StorageKeys.PUBLIC_EMAIL_DOMAINS, value: result.emailRouting.publicEmailDomainList },
diff --git a/core/client/src/sync/VaultSyncEngine.ts b/core/client/src/sync/VaultSyncEngine.ts
index bba711261..9cee5eba7 100644
--- a/core/client/src/sync/VaultSyncEngine.ts
+++ b/core/client/src/sync/VaultSyncEngine.ts
@@ -8,6 +8,7 @@ import { VaultSqlGenerator } from '@aliasvault/vault';
import { NetworkError } from '../api/errors/NetworkError';
import { RequestTimeoutError } from '../api/errors/RequestTimeoutError';
import { WebApiService } from '../api/WebApiService';
+import { VaultKeyService } from '../auth/VaultKeyService';
import { StorageKeys } from '../constants/StorageKeys';
import { AppInfo } from '../platform/AppInfo';
import { getPlatform } from '../platform/ClientPlatform';
@@ -419,13 +420,10 @@ class EngineRun {
}
/**
- * Adopt the key a re-encrypted blob is under, then persist the blob.
+ * Persist the blob.
* @param command - the command
*/
private async storeVault(command: Extract<EngineCommand, { kind: 'vaultStore' }>): Promise<JsonValue> {
- if (command.encryptionKey) {
- await getPlatform().storage.set(StorageKeys.ENCRYPTION_KEY, command.encryptionKey);
- }
const outcome = await this.host.storeVault({
encryptedBlob: command.encryptedBlob,
markDirty: command.markDirty,
@@ -531,11 +529,10 @@ export type VaultSyncOptions = {
*/
export async function buildVaultSyncRequest(operation: VaultSyncOperation, options: VaultSyncOptions = {}): Promise<VaultSyncEngineRequest> {
const storage = getPlatform().storage;
- const [username, encryptionKey, accountPublicKey, accountPrivateKey, isDirty, mutationSequence, privateEmailDomains, isOfflineMode] = await Promise.all([
+ const [username, sessionKeys, accountPublicKey, isDirty, mutationSequence, privateEmailDomains, isOfflineMode] = await Promise.all([
storage.get<string>(StorageKeys.USERNAME),
- storage.get<string>(StorageKeys.ENCRYPTION_KEY),
+ VaultKeyService.getSessionKeys(),
storage.get<string>(StorageKeys.ACCOUNT_PUBLIC_KEY),
- storage.get<string>(StorageKeys.ACCOUNT_PRIVATE_KEY),
storage.get<boolean>(StorageKeys.IS_DIRTY),
storage.get<number>(StorageKeys.MUTATION_SEQUENCE),
storage.get<string[]>(StorageKeys.PRIVATE_EMAIL_DOMAINS),
@@ -545,9 +542,9 @@ export async function buildVaultSyncRequest(operation: VaultSyncOperation, optio
return {
operation,
username: username ?? '',
- encryptionKey: encryptionKey ?? undefined,
+ encryptionKey: sessionKeys?.vaultEncryptionKey,
accountPublicKey: accountPublicKey ?? undefined,
- accountPrivateKey: accountPrivateKey ?? undefined,
+ accountPrivateKey: sessionKeys?.accountPrivateKey ?? undefined,
isDirty: isDirty ?? false,
mutationSequence: mutationSequence ?? 0,
dirtyScopes: isDirty ? await getDirtyScopes() : [],
diff --git a/core/models/src/metadata/EncryptionKeyDerivationParams.ts b/core/models/src/metadata/EncryptionKeyDerivationParams.ts
deleted file mode 100644
index 725d0875a..000000000
--- a/core/models/src/metadata/EncryptionKeyDerivationParams.ts
+++ /dev/null
@@ -1,10 +0,0 @@
-/**
- * These parameters for deriving encryption key from plain text password. These are stored
- * as metadata in the vault upon initial login, and are used to derive the encryption key
- * from the plain text password in the unlock screen.
- */
-export type EncryptionKeyDerivationParams = {
- encryptionType: string,
- encryptionSettings: string,
- salt: string,
-};
diff --git a/core/models/src/metadata/UnlockKeyDerivationParams.ts b/core/models/src/metadata/UnlockKeyDerivationParams.ts
new file mode 100644
index 000000000..cda729a52
--- /dev/null
+++ b/core/models/src/metadata/UnlockKeyDerivationParams.ts
@@ -0,0 +1,9 @@
+/**
+ * The parameters for deriving the unlock key (the KEK) from the plain text master password. Stored on the device
+ * upon login, so the unlock screen can derive the same key again, also offline.
+ */
+export type UnlockKeyDerivationParams = {
+ encryptionType: string,
+ encryptionSettings: string,
+ salt: string,
+};
diff --git a/core/models/src/metadata/index.ts b/core/models/src/metadata/index.ts
index 3e296e642..fa8bf245f 100644
--- a/core/models/src/metadata/index.ts
+++ b/core/models/src/metadata/index.ts
@@ -4,4 +4,4 @@
* optimal vault sync possible.
*/
export * from './VaultMetadata';
-export * from './EncryptionKeyDerivationParams';
+export * from './UnlockKeyDerivationParams';
diff --git a/core/rust/src/vault_sync/engine.rs b/core/rust/src/vault_sync/engine.rs
index 045b5bf38..d6c56802f 100644
--- a/core/rust/src/vault_sync/engine.rs
+++ b/core/rust/src/vault_sync/engine.rs
@@ -293,7 +293,7 @@ fn requiring_pull(server: &HashMap<String, i64>, local: &HashMap<String, i64>) -
}
async fn assert_salt_unchanged(ctx: &Ctx, server_salt: Option<&str>) -> SyncResult<()> {
- let stored: Option<Value> = state::get(&ctx.host, state::ENCRYPTION_KEY_DERIVATION_PARAMS).await?;
+ let stored: Option<Value> = state::get(&ctx.host, state::UNLOCK_KEY_DERIVATION_PARAMS).await?;
let stored_salt = stored.as_ref().and_then(|params| params.get("salt")).and_then(Value::as_str).map(str::to_string);
if let (Some(stored), Some(server)) = (stored_salt, server_salt) {
if !server.is_empty() && server != stored {
diff --git a/core/rust/src/vault_sync/keys.rs b/core/rust/src/vault_sync/keys.rs
index 5f91644cc..9766da223 100644
--- a/core/rust/src/vault_sync/keys.rs
+++ b/core/rust/src/vault_sync/keys.rs
@@ -201,10 +201,11 @@ pub(crate) async fn adopt_hierarchy_created_elsewhere(ctx: &mut Ctx) -> SyncResu
let Some(vault_key) = vault_key else { return Ok(true) };
let Some(encrypted_vek) = vault_key.encrypted_vek.clone() else { return Ok(true) };
+ // Hosts hold the unlock key and derive the vault key from the cached chain.
let adopted: SyncResult<()> = async {
let (vek, account_key) = crypto::resolve_vault_encryption_key(&vault_key.encrypted_account_key, &encrypted_vek, &session_key)?;
- adopt_vek(ctx, &session_key, &vek).await?;
cache_vault_key_blobs(&ctx.host, &vault_key).await?;
+ adopt_vek(ctx, &session_key, &vek).await?;
stage_account_private_key(ctx, &account_key, vault_key.encrypted_account_private_key.as_deref()).await;
Ok(())
}
diff --git a/core/rust/src/vault_sync/state.rs b/core/rust/src/vault_sync/state.rs
index 2c491ab31..353d77cf2 100644
--- a/core/rust/src/vault_sync/state.rs
+++ b/core/rust/src/vault_sync/state.rs
@@ -119,7 +119,7 @@ pub(crate) const ENCRYPTED_VEK: &str = "encryptedVek";
pub(crate) const ENCRYPTED_ACCOUNT_KEY: &str = "encryptedAccountKey";
pub(crate) const ACCOUNT_PUBLIC_KEY: &str = "accountPublicKey";
pub(crate) const ENCRYPTED_ACCOUNT_PRIVATE_KEY: &str = "encryptedAccountPrivateKey";
-pub(crate) const ENCRYPTION_KEY_DERIVATION_PARAMS: &str = "encryptionKeyDerivationParams";
+pub(crate) const UNLOCK_KEY_DERIVATION_PARAMS: &str = "encryptionKeyDerivationParams";
/// Read a value, `None` when absent or null.
pub(crate) async fn get<T: DeserializeOwned>(host: &Host, key: &str) -> SyncResult<Option<T>> {
diff --git a/core/rust/src/vault_sync/tests/mod.rs b/core/rust/src/vault_sync/tests/mod.rs
index 995fe39ec..095fa2861 100644
--- a/core/rust/src/vault_sync/tests/mod.rs
+++ b/core/rust/src/vault_sync/tests/mod.rs
@@ -292,7 +292,7 @@ fn expired_session_requires_logout() {
fn password_changed_elsewhere_requires_logout() {
let vek = crypto::generate_key_base64();
let mut host = TestHost::new(&vek);
- host.state.insert(state::ENCRYPTION_KEY_DERIVATION_PARAMS.to_string(), json!({ "salt": "old-salt", "encryptionType": "Argon2Id", "encryptionSettings": "{}" }));
+ host.state.insert(state::UNLOCK_KEY_DERIVATION_PARAMS.to_string(), json!({ "salt": "old-salt", "encryptionType": "Argon2Id", "encryptionSettings": "{}" }));
host.respond("GET", "Status", json!({ "clientVersionSupported": true, "serverVersion": "0.31.0", "manifestRevisions": [], "personalManifestId": PERSONAL_MANIFEST_ID, "srpSalt": "new-salt" }));
let result = host.drive(&SyncSession::new(&request("fullSync", &vek, false, 0)).unwrap());
@@ -346,6 +346,7 @@ fn manifest_migration_generates_the_key_hierarchy_and_pushes() {
assert_eq!(*vek, new_key);
assert!(host.state.contains_key(state::ENCRYPTED_ACCOUNT_KEY));
assert!(result["sessionUpdates"]["accountPrivateKey"].is_string());
+ assert_eq!(host.rekeyed_stores_found_the_chain, vec![true], "the chain is cached before the vault is stored under the VEK");
}
/// The latest EF migration stamp of a database.
@@ -520,6 +521,7 @@ fn a_hierarchy_created_on_another_device_is_adopted_on_the_next_pull() {
assert_eq!(item_names(&host.local), vec!["Server item"]);
assert_eq!(host.state[state::ENCRYPTED_ACCOUNT_KEY], hierarchy.account_keys.encrypted_account_key);
assert_eq!(host.state[state::ACCOUNT_PUBLIC_KEY], hierarchy.account_keys.account_public_key);
+ assert_eq!(host.rekeyed_stores_found_the_chain, vec![true], "the chain is cached before the vault is stored under the VEK");
}
/// Login: the host hands the password-derived key to `resolveVaultKey`; the server's chain opens with it, is
diff --git a/core/rust/src/vault_sync/tests/test_host.rs b/core/rust/src/vault_sync/tests/test_host.rs
index 06a9d756b..c06f3ae93 100644
--- a/core/rust/src/vault_sync/tests/test_host.rs
+++ b/core/rust/src/vault_sync/tests/test_host.rs
@@ -32,6 +32,7 @@ pub struct TestHost {
pub is_dirty: bool,
pub mark_clean_calls: Vec<u64>,
pub store_calls: Vec<Command>,
+ pub rekeyed_stores_found_the_chain: Vec<bool>,
pub requests: Vec<RecordedRequest>,
pub responders: Vec<Responder>,
pub logs: Vec<String>,
@@ -75,6 +76,7 @@ impl TestHost {
is_dirty: false,
mark_clean_calls: Vec::new(),
store_calls: Vec::new(),
+ rekeyed_stores_found_the_chain: Vec::new(),
requests: Vec::new(),
responders: Vec::new(),
logs: Vec::new(),
@@ -148,6 +150,10 @@ impl TestHost {
Command::VaultStore { encrypted_blob, mark_dirty, encryption_key, expected_mutation_seq, revision } => {
self.store_calls.push(Command::VaultStore { encrypted_blob: String::new(), mark_dirty, encryption_key: encryption_key.clone(), expected_mutation_seq, revision });
if let Some(key) = encryption_key {
+ // The app hosts hold the unlock key and derive the vault key from the cached chain.
+ let found_the_chain = self.state.contains_key("encryptedAccountKey") && self.state.contains_key("encryptedVek");
+ assert!(found_the_chain, "a vault stored under a new key needs the chain that opens it cached first");
+ self.rekeyed_stores_found_the_chain.push(found_the_chain);
self.vault_key = key;
}
if let Some(expected) = expected_mutation_seq {