Privacy-first password manager with built-in email aliasing. Fully encrypted and self-hostable.
Add vault key local handling scaffolding (#2159)
Leendert de Borst6e85786e0ac8
diff --git a/apps/browser-extension/src/entrypoints/background/VaultMessageHandler.ts b/apps/browser-extension/src/entrypoints/background/VaultMessageHandler.tsindex 040bd0024..4797392a1 100644--- a/apps/browser-extension/src/entrypoints/background/VaultMessageHandler.ts+++ b/apps/browser-extension/src/entrypoints/background/VaultMessageHandler.ts@@ -33,6 +33,7 @@ import { VaultResponse as messageVaultResponse } from '@/utils/types/messaging/Vimport { VaultUploadResponse as messageVaultUploadResponse } from '@/utils/types/messaging/VaultUploadResponse';import { type VaultMutationScope, ALL_VAULT_MUTATION_SCOPES, DEFAULT_VAULT_MUTATION_SCOPE, dirtyScopeStorageKey, isManifestScope } from '@/utils/types/VaultMutationScope';import { VaultCodec } from '@/utils/VaultCodec';+import { VaultKeyService, WRAPPED_VEK_STORAGE_KEY } from '@/utils/VaultKeyService';import { vaultMergeService } from '@/utils/VaultMergeService';import { vaultSyncService, SERVER_MANIFEST_REVISIONS_STORAGE_KEY } from '@/utils/VaultSyncService';import { WebApiService } from '@/utils/WebApiService';@@ -263,7 +264,7 @@ async function fetchLatestVaultFromServer(): Promise<VaultResponse> {*/async function uploadVaultV2(sqliteClient: SqliteClient): Promise<VaultPostResponse> {// Surfaces ServerUpdateRequiredError for servers that do not support the v2 API before we attempt the push.- await vaultSyncService.checkStatus();+ const syncStatus = await vaultSyncService.checkStatus();const encryptionKey = await handleGetEncryptionKey();if (!encryptionKey) {@@ -273,9 +274,20 @@ async function uploadVaultV2(sqliteClient: SqliteClient): Promise<VaultPostRespoconst username = (await storage.getItem('local:username')) as string;const emailAddresses = await getEmailAddressesForVault(sqliteClient);- const result = await vaultSyncService.push(sqliteClient, encryptionKey, username, emailAddresses);+ /*+ * KEK/VEK migration: when the server has no vault key yet, this push generates a VEK, re-encrypts everything+ * with it, and creates the vault key server-side (wrapping the VEK with the current password-derived key).+ * Guarded on vaultKeySupported: a server that predates vault keys would silently drop createVaultKey while+ * storing the VEK-encrypted payload, which would strand every other device. Such servers get a normal push.+ */+ const result = await vaultSyncService.push(sqliteClient, encryptionKey, username, emailAddresses, { createVaultKey: syncStatus.vaultKeySupported && !syncStatus.hasVaultKey });if (result.status === 'ok') {+ if (result.newEncryptionKey) {+ // Migration succeeded: from now on the session key is the VEK, not the password-derived key.+ await handleStoreEncryptionKey(result.newEncryptionKey);+ }+return { status: 0, newRevisionNumber: result.newManifestRevision ?? 0 };}@@ -445,6 +457,7 @@ export async function handleClearVaultData(): Promise<messageBoolResponse> {'local:mutationSequence','local:isOfflineMode','local:encryptionKeyDerivationParams',+ WRAPPED_VEK_STORAGE_KEY,'local:username',]);@@ -808,6 +821,16 @@ async function uploadDirtyBucketsOnly(sqliteClient: SqliteClient, scopes: VaultMthrow new Error(formatErrorWithCode(await t('common.errors.vaultIsLocked'), AppErrorCode.VAULT_LOCKED));}+ /*+ * A bucket-only push encrypts with the current session key. As long as the user has no vault key yet, the full+ * upload path must run instead so the KEK/VEK migration re-keys the whole vault in one atomic request.+ */+ const syncStatus = await vaultSyncService.checkStatus();+ if (syncStatus.vaultKeySupported && !syncStatus.hasVaultKey) {+ devLog('[V2Push] User has no vault key yet, falling back to full vault upload to run the KEK/VEK migration.');+ return (await uploadNewVaultToServer(sqliteClient)).response;+ }+/** Which tables make up each bucket category is owned by the Rust layer.*/@@ -1021,8 +1044,13 @@ async function uploadNewVaultToServer(sqliteClient: SqliteClient) : Promise<{ rethrow err;}- // Re-encrypt and persist locally so handleGetVault / readers continue to work without a re-sync.- const reEncrypted = await EncryptionUtility.symmetricEncrypt(updatedVaultData, encryptionKey);+ /*+ * Re-encrypt and persist locally so handleGetVault / readers continue to work without a re-sync. Re-fetch the+ * session key: a KEK/VEK migration inside uploadVaultV2 swaps it to the freshly generated VEK, and the local+ * copy must be encrypted with the same key the next reader will use.+ */+ const currentKey = await handleGetEncryptionKey() ?? encryptionKey;+ const reEncrypted = await EncryptionUtility.symmetricEncrypt(updatedVaultData, currentKey);await storage.setItem('local:encryptedVault', reEncrypted);if (v2Response.status === 0) {await storage.setItem('local:serverRevision', v2Response.newRevisionNumber);@@ -1243,6 +1271,58 @@ export async function handleGetServerRevision(): Promise<number> {return revision ?? 0;}+/**+ * Adopt a vault key created by another device (KEK/VEK migration race, or another client migrating while this one+ * holds a live session). When the server reports a vault key but this session still holds the raw password-derived+ * key (recognizable by the missing cached wrapped VEK), fetch the vault key, unwrap the VEK with the derived key,+ * swap the session key, and re-encrypt the locally persisted vault with the VEK. Returns false when adoption fails+ * (VEK cannot be unwrapped with the current session key): the caller must force a re-login.+ * @param statusResponse - the status response from the server+ */+async function adoptRemoteVaultKeyIfNeeded(statusResponse: StatusResponseV2): Promise<boolean> {+ if (statusResponse.hasVaultKey !== true) {+ return true;+ }++ const wrappedVek = await storage.getItem(WRAPPED_VEK_STORAGE_KEY) as string | null;+ if (wrappedVek) {+ // Already on the KEK/VEK model: the session key is the VEK.+ return true;+ }++ const sessionKey = await handleGetEncryptionKey();+ if (!sessionKey) {+ // Vault is locked; the next unlock/login resolves the key through the vault key endpoint.+ return true;+ }++ try {+ const fetchResult = await VaultKeyService.fetchVaultKey();+ if (!fetchResult.vaultKey) {+ return true;+ }++ const vek = await EncryptionUtility.unwrapVaultEncryptionKey(fetchResult.vaultKey.wrappedVek, sessionKey);++ // Re-encrypt the locally persisted vault with the VEK before swapping the session key.+ const encryptedVault = await storage.getItem('local:encryptedVault') as string | null;+ if (encryptedVault) {+ const decrypted = await EncryptionUtility.symmetricDecrypt(encryptedVault, sessionKey);+ await storage.setItem('local:encryptedVault', await EncryptionUtility.symmetricEncrypt(decrypted, vek));+ }++ await storage.setItem(WRAPPED_VEK_STORAGE_KEY, fetchResult.vaultKey.wrappedVek);+ await handleStoreEncryptionKey(vek);+ cachedSqliteClient = null;+ cachedVaultBlob = null;+ devLog('[VaultSync] Adopted vault key created by another client; session key swapped to the VEK.');+ return true;+ } catch (error) {+ devError('[VaultSync] Failed to adopt remote vault key, forcing re-login:', error);+ return false;+ }+}+/*** Result of a sync status check (without doing actual sync).*/@@ -1320,6 +1400,11 @@ export async function handleCheckSyncStatus(): Promise<SyncStatusCheckResult> {return { success: false, hasNewerVault: false, hasDirtyChanges: false, isOffline: false, requiresLogout: true, errorKey: 'passwordChanged' };}+ // Adopt a vault key created by another device before any sync work happens.+ if (!await adoptRemoteVaultKeyIfNeeded(statusResponse)) {+ return { success: false, hasNewerVault: false, hasDirtyChanges: false, isOffline: false, requiresLogout: true, errorKey: 'passwordChanged' };+ }+const localSharedRevisions = await getLocalSharedManifestRevisions();return {@@ -1448,6 +1533,11 @@ async function handleFullVaultSyncInternal(): Promise<FullVaultSyncResult> {return { success: false, hasNewVault: false, wasOffline: false, upgradeRequired: false, requiresLogout: true, errorKey: 'passwordChanged' };}+ // Adopt a vault key created by another device before any sync work happens.+ if (!await adoptRemoteVaultKeyIfNeeded(statusResponse)) {+ return { success: false, hasNewVault: false, wasOffline: false, upgradeRequired: false, requiresLogout: true, errorKey: 'passwordChanged' };+ }+// Valid connection - exit offline mode if we were in itconst isOffline = await storage.getItem('local:isOfflineMode') as boolean | null;if (isOffline) {diff --git a/apps/browser-extension/src/entrypoints/popup/pages/auth/Login.tsx b/apps/browser-extension/src/entrypoints/popup/pages/auth/Login.tsxindex bd0717907..f3dc1b7c5 100644--- a/apps/browser-extension/src/entrypoints/popup/pages/auth/Login.tsx+++ b/apps/browser-extension/src/entrypoints/popup/pages/auth/Login.tsx@@ -26,6 +26,7 @@ import { hasErrorCode, getErrorMessage } from '@/utils/types/errors/AppErrorCodeimport { ServerUpdateRequiredError } from '@/utils/types/errors/ServerUpdateRequiredError';import { VaultProcessingError } from '@/utils/types/errors/VaultProcessingError';import type { MobileLoginResult } from '@/utils/types/messaging/MobileLoginResult';+import { VaultKeyService } from '@/utils/VaultKeyService';import { vaultSyncService } from '@/utils/VaultSyncService';import { vaultStateEvents } from '@/events/VaultStateEvents';@@ -155,8 +156,14 @@ const Login: React.FC = () => {// Store auth info first — the vault fetch below makes an authenticated request via the stored access token.await app.setAuthTokens(username, token, refreshToken);+ /*+ * KEK/VEK: for migrated accounts the derived key is only the KEK; fetch the vault key and unwrap the VEK,+ * which becomes the session encryption key. Legacy accounts keep using the derived key directly.+ */+ const { encryptionKey } = await VaultKeyService.resolveEncryptionKey(passwordHashBase64, webApi);+// Store the encryption key and derivation params separately- await dbContext.storeEncryptionKey(passwordHashBase64);+ await dbContext.storeEncryptionKey(encryptionKey);await dbContext.storeEncryptionKeyDerivationParams({salt: loginResponse.salt,encryptionType: loginResponse.encryptionType,@@ -164,7 +171,7 @@ const Login: React.FC = () => {});// Fetch the latest vault.- const vaultResponseJson = await vaultSyncService.pull(passwordHashBase64);+ const vaultResponseJson = await vaultSyncService.pull(encryptionKey);/** Persist and load the vault.@@ -174,7 +181,7 @@ const Login: React.FC = () => {* - If server is more advanced > uses server vault* - If password changed (can't decrypt) > uses server vault*/- await persistAndLoadVault(vaultResponseJson, passwordHashBase64, username);+ await persistAndLoadVault(vaultResponseJson, encryptionKey, username);// Reset prefill flag so next logout will prefill againusernamePrefillAttempted = false;@@ -454,8 +461,16 @@ 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 VEK for migrated accounts, or the derived key when+ * the mobile app predates the KEK/VEK model). Refresh the local wrapped-VEK cache so offline password unlock+ * keeps working, then upgrade the received key to the VEK when it turns out to be the KEK.+ */+ await VaultKeyService.cacheWrappedVekFromServer(webApi);+ const { key: mobileKey } = await VaultKeyService.upgradeStoredKeyIfNeeded(result.decryptionKey);+// Store the encryption key and derivation params- await dbContext.storeEncryptionKey(result.decryptionKey);+ await dbContext.storeEncryptionKey(mobileKey);await dbContext.storeEncryptionKeyDerivationParams({salt: result.salt,encryptionType: result.encryptionType,@@ -463,10 +478,10 @@ const Login: React.FC = () => {});// Fetch the latest vault.- const vaultResponse = await vaultSyncService.pull(result.decryptionKey);+ const vaultResponse = await vaultSyncService.pull(mobileKey);// Persist and load the vault- await persistAndLoadVault(vaultResponse, result.decryptionKey, result.username);+ await persistAndLoadVault(vaultResponse, mobileKey, result.username);/** Navigate to reinitialize page which will:diff --git a/apps/browser-extension/src/entrypoints/popup/pages/auth/Unlock.tsx b/apps/browser-extension/src/entrypoints/popup/pages/auth/Unlock.tsxindex 4f34b2bce..ecc5b5985 100644--- a/apps/browser-extension/src/entrypoints/popup/pages/auth/Unlock.tsx+++ b/apps/browser-extension/src/entrypoints/popup/pages/auth/Unlock.tsx@@ -29,11 +29,13 @@ import {IncorrectPinError,InvalidPinFormatError,resetFailedAttempts,+ setupPin,unlockWithPin} from '@/utils/PinUnlockService';import { hasErrorCode, getErrorMessage, extractErrorCode, AppErrorCode } from '@/utils/types/errors/AppErrorCodes';import { VaultVersionIncompatibleError } from '@/utils/types/errors/VaultVersionIncompatibleError';import type { MobileLoginResult } from '@/utils/types/messaging/MobileLoginResult';+import { VaultKeyService } from '@/utils/VaultKeyService';import { vaultStateEvents } from '@/events/VaultStateEvents';@@ -275,14 +277,19 @@ const Unlock: React.FC = () => {loginResponse.encryptionType,loginResponse.encryptionSettings);- passwordHashBase64 = credentials.passwordHashBase64;-// Store encryption params for future offline unlockawait dbContext.storeEncryptionKeyDerivationParams({salt: loginResponse.salt,encryptionType: loginResponse.encryptionType,encryptionSettings: loginResponse.encryptionSettings,});++ /*+ * KEK/VEK: for migrated accounts the derived key is only the KEK; unwrap 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.+ */+ passwordHashBase64 = (await VaultKeyService.resolveEncryptionKey(credentials.passwordHashBase64, webApi)).encryptionKey;} else {// Offline mode: use stored encryption params to derive keyconst storedParams = await sendMessage('GET_ENCRYPTION_KEY_DERIVATION_PARAMS');@@ -301,7 +308,12 @@ const Unlock: React.FC = () => {storedParams.encryptionType,storedParams.encryptionSettings);- passwordHashBase64 = credentials.passwordHashBase64;++ /*+ * KEK/VEK offline: unwrap the locally cached wrapped VEK with the derived key. Throws a decrypt-failed+ * (E-203) error on a wrong password. Legacy accounts (no cached wrapped VEK) use the derived key directly.+ */+ passwordHashBase64 = await VaultKeyService.resolveEncryptionKeyOffline(credentials.passwordHashBase64);// Set offline modeawait dbContext.setIsOffline(true);@@ -410,7 +422,18 @@ const Unlock: React.FC = () => {try {// Unlock with PIN - this derives the encryption key from the PIN- const passwordHashBase64 = await unlockWithPin(pinToUse);+ 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 refresh the PIN store so future PIN unlocks+ * return the VEK directly.+ */+ const upgrade = await VaultKeyService.upgradeStoredKeyIfNeeded(passwordHashBase64);+ if (upgrade.upgraded) {+ passwordHashBase64 = upgrade.key;+ await setupPin(pinToUse, passwordHashBase64);+ }// Check if we're online or offline (for offline mode flag)const statusResult = await checkStatus();@@ -558,8 +581,16 @@ const Unlock: React.FC = () => {// Set new auth tokensawait 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 wrapped-VEK cache so offline password unlock+ * keeps working, then upgrade the received key to the VEK when it turns out to be the KEK.+ */+ await VaultKeyService.cacheWrappedVekFromServer(webApi);+ const { key: mobileKey } = await VaultKeyService.upgradeStoredKeyIfNeeded(result.decryptionKey);+// Store the encryption key and derivation params- await dbContext.storeEncryptionKey(result.decryptionKey);+ await dbContext.storeEncryptionKey(mobileKey);await dbContext.storeEncryptionKeyDerivationParams({salt: result.salt,encryptionType: result.encryptionType,diff --git a/apps/browser-extension/src/utils/EncryptionUtility.ts b/apps/browser-extension/src/utils/EncryptionUtility.tsindex afc956bd7..a98c2e1bb 100644--- a/apps/browser-extension/src/utils/EncryptionUtility.ts+++ b/apps/browser-extension/src/utils/EncryptionUtility.ts@@ -186,6 +186,32 @@ export class EncryptionUtility {return new Uint8Array(decrypted);}+ /**+ * Generates a random 256-bit Vault Encryption Key (VEK) as base64. The VEK encrypts the vault content and never+ * changes; it is stored server-side only in wrapped form (encrypted with a KEK derived from an unlock method).+ */+ public static generateVaultEncryptionKey(): string {+ const vek = crypto.getRandomValues(new Uint8Array(32));+ return btoa(String.fromCharCode(...vek));+ }++ /**+ * Wraps (encrypts) a VEK with a KEK using AES-256-GCM. Returns base64(IV | ciphertext | authTag).+ */+ public static async wrapVaultEncryptionKey(vekBase64: string, kekBase64: string): Promise<string> {+ const vekBytes = Uint8Array.from(atob(vekBase64), c => c.charCodeAt(0));+ return this.symmetricEncryptBytes(vekBytes, kekBase64);+ }++ /**+ * Unwraps (decrypts) a wrapped VEK with a KEK. Returns the VEK as base64.+ */+ public static async unwrapVaultEncryptionKey(wrappedVekBase64: string, kekBase64: string): Promise<string> {+ const wrappedBytes = Uint8Array.from(atob(wrappedVekBase64), c => c.charCodeAt(0));+ const vekBytes = await this.symmetricDecryptBytes(wrappedBytes, kekBase64);+ return btoa(String.fromCharCode(...vekBytes));+ }+/*** Generates a new RSA key pair for asymmetric encryption*/diff --git a/apps/browser-extension/src/utils/VaultKeyService.ts b/apps/browser-extension/src/utils/VaultKeyService.tsnew file mode 100644index 000000000..def8ba075--- /dev/null+++ b/apps/browser-extension/src/utils/VaultKeyService.ts@@ -0,0 +1,163 @@+/**+ * VaultKeyService.+ *+ * Client-side helper for the KEK/VEK model. The vault content is encrypted with a random Vault Encryption Key+ * (VEK) that never changes; the server stores the VEK wrapped (AES-256-GCM) with a Key Encryption Key (KEK)+ * derived from the master password. This service resolves which key the rest of the app should use as "the+ * encryption key": the unwrapped VEK for migrated users, or the password-derived key itself for legacy users.+ */++import { storage } from 'wxt/utils/storage';++import type { VaultKeyGetResponse, VaultKeyResponse } from '@/utils/dist/core/models/webapi';+import { EncryptionUtility } from '@/utils/EncryptionUtility';+import { ApiRequestError } from '@/utils/types/errors/ApiRequestError';+import { AppErrorCode, formatErrorWithCode } from '@/utils/types/errors/AppErrorCodes';+import { WebApiService } from '@/utils/WebApiService';++/** Local cache of the wrapped VEK (AES-GCM ciphertext) enabling offline unlock for migrated users. */+export const WRAPPED_VEK_STORAGE_KEY = 'local:wrappedVek';++/** The key type for password-based vault keys, mirroring the server's VaultKey.KeyType value. */+export const VAULT_KEY_TYPE_PASSWORD = 'password';++/**+ * Result of resolving the vault encryption key after deriving the password key.+ */+export type ResolvedEncryptionKey = {+ /** The key to use for all vault encryption/decryption: the VEK for migrated users, the derived key for legacy users. */+ encryptionKey: string;+ /** The wrapped VEK when the user is on the KEK/VEK model, null for legacy users. */+ wrappedVek: string | null;+};++/**+ * Result of fetching the vault key from the server.+ */+export type FetchVaultKeyResult = {+ /** False when the server does not implement the VaultKey endpoint at all (older server version, HTTP 404). */+ supported: boolean;+ /** The vault key, or null when the user has none (legacy user) or the endpoint is unsupported. */+ vaultKey: VaultKeyResponse | null;+};++/**+ * Static helper for fetching, unwrapping, and caching the vault encryption key (VEK).+ */+export class VaultKeyService {+ /**+ * Fetch the current user's password vault key from the server.+ * @param webApi - the API client to use (popup context passes its own instance; background creates one)+ */+ public static async fetchVaultKey(webApi?: WebApiService): Promise<FetchVaultKeyResult> {+ const api = webApi ?? new WebApiService();+ try {+ const response = await api.get<VaultKeyGetResponse>(`VaultKey/${VAULT_KEY_TYPE_PASSWORD}`);+ return { supported: true, vaultKey: response.vaultKey ?? null };+ } catch (e) {+ if (e instanceof ApiRequestError && e.statusCode === 404) {+ return { supported: false, vaultKey: null };+ }+ if (e instanceof Error && e.message.includes('status: 404')) {+ return { supported: false, vaultKey: null };+ }+ throw e;+ }+ }++ /**+ * Resolve the vault encryption key right after authentication: fetch the vault key from the server, unwrap the+ * VEK with the password-derived key (KEK), and cache the wrapped VEK for offline unlock. For legacy users+ * (server explicitly reports no vault key) the derived key itself is the encryption key and any stale cached+ * wrapped VEK is cleared.+ * @param derivedKeyBase64 - the password-derived key (the KEK)+ * @param webApi - the API client to use+ * @throws Error with {@link AppErrorCode.VAULT_DECRYPT_FAILED} when the wrapped VEK cannot be unwrapped with the+ * derived key (wrong password, or key material out of sync).+ */+ public static async resolveEncryptionKey(derivedKeyBase64: string, webApi?: WebApiService): Promise<ResolvedEncryptionKey> {+ const result = await VaultKeyService.fetchVaultKey(webApi);++ if (!result.supported) {+ // Older server: trust the local cache. Legacy accounts have no cached wrapped VEK and use the derived key.+ const cachedWrappedVek = await storage.getItem(WRAPPED_VEK_STORAGE_KEY) as string | null;+ if (!cachedWrappedVek) {+ return { encryptionKey: derivedKeyBase64, wrappedVek: null };+ }++ return { encryptionKey: await VaultKeyService.unwrapOrThrow(cachedWrappedVek, derivedKeyBase64), wrappedVek: cachedWrappedVek };+ }++ if (!result.vaultKey) {+ await storage.removeItem(WRAPPED_VEK_STORAGE_KEY);+ return { encryptionKey: derivedKeyBase64, wrappedVek: null };+ }++ const vek = await VaultKeyService.unwrapOrThrow(result.vaultKey.wrappedVek, derivedKeyBase64);+ await storage.setItem(WRAPPED_VEK_STORAGE_KEY, result.vaultKey.wrappedVek);+ return { encryptionKey: vek, wrappedVek: result.vaultKey.wrappedVek };+ }++ /**+ * Resolve the vault encryption key offline: unwrap the locally cached wrapped VEK with the derived key. For+ * legacy users (no cached wrapped VEK) the derived key itself is returned.+ * @param derivedKeyBase64 - the password-derived key+ * @throws Error with {@link AppErrorCode.VAULT_DECRYPT_FAILED} when unwrapping fails (wrong password).+ */+ public static async resolveEncryptionKeyOffline(derivedKeyBase64: string): Promise<string> {+ const wrappedVek = await storage.getItem(WRAPPED_VEK_STORAGE_KEY) as string | null;+ if (!wrappedVek) {+ return derivedKeyBase64;+ }++ return VaultKeyService.unwrapOrThrow(wrappedVek, derivedKeyBase64);+ }++ /**+ * Refresh the local wrapped-VEK cache from the server without needing the KEK.+ * @param webApi - the API client to use+ */+ public static async cacheWrappedVekFromServer(webApi?: WebApiService): Promise<void> {+ const result = await VaultKeyService.fetchVaultKey(webApi);+ if (result.vaultKey) {+ await storage.setItem(WRAPPED_VEK_STORAGE_KEY, result.vaultKey.wrappedVek);+ } else if (result.supported) {+ await storage.removeItem(WRAPPED_VEK_STORAGE_KEY);+ }+ }++ /**+ * Given a key restored from an auxiliary unlock method (PIN, mobile QR), return the key to actually use.+ * @param storedKey - the key restored from the auxiliary unlock method+ */+ public static async upgradeStoredKeyIfNeeded(storedKey: string): Promise<{ key: string; upgraded: boolean }> {+ const wrappedVek = await storage.getItem(WRAPPED_VEK_STORAGE_KEY) as string | null;+ if (!wrappedVek) {+ return { key: storedKey, upgraded: false };+ }++ try {+ const vek = await EncryptionUtility.unwrapVaultEncryptionKey(wrappedVek, storedKey);+ return { key: vek, upgraded: true };+ } catch {+ return { key: storedKey, upgraded: false };+ }+ }++ /**+ * Unwrap a wrapped VEK, mapping an AES-GCM authentication failure onto the standard decrypt-failed error code so+ * existing wrong-password handling applies.+ * @param wrappedVek - base64(IV ‖ ciphertext ‖ tag) of the wrapped VEK+ * @param kekBase64 - the password-derived KEK+ */+ private static async unwrapOrThrow(wrappedVek: string, kekBase64: string): Promise<string> {+ try {+ return await EncryptionUtility.unwrapVaultEncryptionKey(wrappedVek, kekBase64);+ } catch {+ // E-203: unwrap failed, which for the password key type means the entered password is wrong.+ throw new Error(formatErrorWithCode('Failed to unwrap vault encryption key', AppErrorCode.VAULT_DECRYPT_FAILED));+ }+ }+}++export default VaultKeyService;diff --git a/apps/browser-extension/src/utils/VaultSyncService.ts b/apps/browser-extension/src/utils/VaultSyncService.tsindex 441134c1e..2fab67a07 100644--- a/apps/browser-extension/src/utils/VaultSyncService.ts+++ b/apps/browser-extension/src/utils/VaultSyncService.ts@@ -16,6 +16,7 @@ import { SqliteClient } from '@/utils/SqliteClient';import { ServerUpdateRequiredError } from '@/utils/types/errors/ServerUpdateRequiredError';import { VaultProcessingError } from '@/utils/types/errors/VaultProcessingError';import { type BlobEntry, type VaultManifest, type VaultDataBucket, VaultCodec } from '@/utils/VaultCodec';+import { VAULT_KEY_TYPE_PASSWORD, WRAPPED_VEK_STORAGE_KEY } from '@/utils/VaultKeyService';import { WebApiService } from '@/utils/WebApiService';// Endpoints are relative; WebApiService resolves them under the API's /v2/ prefix.@@ -115,6 +116,14 @@ const SETTINGS_BUCKET_CATEGORY = VaultDataBucketCategory.Settings;export type VaultSyncStatus = {/** Whether the user has been migrated to manifest-v1 storage (false = still legacy, migrate on next save). */isMigrated: boolean;+ /** Whether the user has a vault key (KEK/VEK model). False = the next full upload must carry createVaultKey. */+ hasVaultKey: boolean;+ /**+ * Whether the server understands vault keys at all (the hasVaultKey field was present in its status response).+ * A KEK/VEK migration must never be attempted against a server that would silently drop createVaultKey: the+ * upload would be VEK-encrypted while the wrapped VEK is never stored, stranding every other device.+ */+ vaultKeySupported: boolean;manifestRevision: number | null;settingsRevision: number | null;};@@ -145,6 +154,11 @@ export type PushResult = {status: 'ok' | 'outdated' | 'missing-blobs' | 'rejected';newManifestRevision: number | null;reasons?: string[];+ /**+ * Set when this push performed the KEK/VEK migration: the freshly generated VEK the caller must adopt as the+ * session encryption key (the old password-derived key is now only the KEK).+ */+ newEncryptionKey?: string;};type BlobRefDto = { hash: string; category: string };@@ -212,6 +226,7 @@ type StatusResponseDto = {storageFormat: number;manifestRevisions: ManifestRevisionDto[];bucketRevisions: BucketRevisionDto[];+ hasVaultKey?: boolean;};type UploadResponseDto = {@@ -291,6 +306,8 @@ export class VaultSyncService {const rootManifestRevision = revisions.find(m => m.isRoot)?.revision ?? null;return {isMigrated: dto.storageFormat === STORAGE_FORMAT_MANIFEST,+ hasVaultKey: dto.hasVaultKey === true,+ vaultKeySupported: dto.hasVaultKey !== undefined,manifestRevision: rootManifestRevision,settingsRevision,};@@ -505,17 +522,32 @@ export class VaultSyncService {* reports missing blobs still missing (stale local knowledge, e.g. server-side GC), the missing bytes are uploaded* and the POST retried once.* @param sqliteClient - the in-memory SQLite the user has been editing- * @param vek - the symmetric encryption key+ * @param vek - the symmetric encryption key (on a KEK/VEK migration push this is the password-derived key,+ * which becomes the KEK; on a normal push it is the VEK itself)* @param username - the user's username (sent in the upload payload for cross-check)* @param emailAddressList - claimed email aliases (server needs these in plaintext for routing)+ * @param options - set createVaultKey to perform the KEK/VEK migration as part of this push* @returns Push outcome.*/public async push(sqliteClient: SqliteClient,vek: string,username: string,- emailAddressList: string[]+ emailAddressList: string[],+ options?: { createVaultKey?: boolean }): Promise<PushResult> {+ /*+ * KEK/VEK migration: on the first push after this feature ships, generate a fresh VEK and encrypt everything+ * with it; the passed-in password-derived key becomes the KEK that wraps the VEK. On a normal push the+ * passed-in key IS the VEK and is used directly.+ */+ const migrateToVaultKey = options?.createVaultKey === true;+ const contentKey = migrateToVaultKey ? EncryptionUtility.generateVaultEncryptionKey() : vek;+ const wrappedVek = migrateToVaultKey ? await EncryptionUtility.wrapVaultEncryptionKey(contentKey, vek) : null;+ if (migrateToVaultKey) {+ devLog('[V2Push] KEK/VEK migration: generated new VEK, vault content and all blobs will be re-encrypted and re-uploaded.');+ }+// 1) Canonicalize using the persisted user salt (or generate one on first save).let userSalt = (await storage.getItem(SALT_STORAGE_KEY)) as string | null;if (!userSalt) {@@ -569,7 +601,7 @@ export class VaultSyncService {// 3) Pack then AES-GCM encrypt.const manifestPlaintext = await timedStage('stringify-manifest', () => JSON.stringify(canonicalized.manifest));- const { ciphertext: manifestCiphertext, compressedBytes: manifestCompressedBytes } = await packEncrypt(manifestPlaintext, vek);+ const { ciphertext: manifestCiphertext, compressedBytes: manifestCompressedBytes } = await packEncrypt(manifestPlaintext, contentKey);const manifestCiphertextHash = await vaultCodecComputeCiphertextHash(manifestCiphertext);devLog(`[V2Push] Manifest blob: raw ${formatKb(manifestPlaintext.length)} → compressed ${formatKb(manifestCompressedBytes)} → encrypted ${formatKb(manifestCiphertext.length)}.`);@@ -577,7 +609,7 @@ export class VaultSyncService {const bucketDtos: Array<{ category: string; blob: string; ciphertextHash: string }> = [];for (const bucket of canonicalized.dataBuckets) {const bucketPlaintext = JSON.stringify(bucket);- const { ciphertext, compressedBytes } = await packEncrypt(bucketPlaintext, vek);+ const { ciphertext, compressedBytes } = await packEncrypt(bucketPlaintext, contentKey);const ciphertextHash = await vaultCodecComputeCiphertextHash(ciphertext);bucketDtos.push({ category: bucket.category, blob: ciphertext, ciphertextHash });devLog(`[V2Push] Data bucket "${bucket.category}": raw ${formatKb(bucketPlaintext.length)} → compressed ${formatKb(compressedBytes)} → encrypted ${formatKb(ciphertext.length)}.`);@@ -594,15 +626,21 @@ export class VaultSyncService {const candidates = allBlobHashes.filter(h => !knownServerHashes.has(h));let hashesToUpload: string[] = [];- if (candidates.length > 0) {+ if (migrateToVaultKey) {+ /*+ * The blob content hashes are plaintext-based and thus unchanged, but every stored ciphertext was encrypted+ * with the old key. Re-encrypt and re-upload all of them with the new VEK (server overwrites in place).+ */+ hashesToUpload = allBlobHashes;+ } else if (candidates.length > 0) {const missingResp = await webApi.post<{ hashes: string[] }, MissingBlobsResponseDto>(BLOBS_MISSING_ENDPOINT, { hashes: candidates });hashesToUpload = missingResp.missing ?? [];}- devLog(`[V2Push] Blob diff: ${allBlobHashes.length} blobs in vault, ${candidates.length} not known to be on server, ${hashesToUpload.length} confirmed missing → uploading ${hashesToUpload.length}.`);+ devLog(`[V2Push] Blob diff: ${allBlobHashes.length} blobs in vault, ${candidates.length} not known to be on server, uploading ${hashesToUpload.length}${migrateToVaultKey ? ' (all, VEK migration)' : ''}.`);// Pre-upload the missing blobs in size-capped batches so the manifest POST below carries references only.- const uploadedCiphertexts = await this.uploadBlobs(webApi, blobEntries, hashesToUpload, vek);+ const uploadedCiphertexts = await this.uploadBlobs(webApi, blobEntries, hashesToUpload, contentKey, migrateToVaultKey);const blobReferences: BlobRefDto[] = Array.from(blobEntries.entries()).map(([hash, entry]) => ({hash,@@ -624,6 +662,7 @@ export class VaultSyncService {blobReferences,emailRouting: { emailAddressList },encryptionPublicKey: '',+ createVaultKey: wrappedVek ? { keyType: VAULT_KEY_TYPE_PASSWORD, wrappedVek } : null,};let resp = await webApi.post<typeof payload, UploadResponseDto>(UPLOAD_ENDPOINT, payload);@@ -639,7 +678,7 @@ export class VaultSyncService {}devWarn(`[V2Sync] Server reported ${resp.missingBlobHashes.length} missing blob(s); uploading and retrying once.`);- const retried = await this.uploadBlobs(webApi, blobEntries, resp.missingBlobHashes, vek);+ const retried = await this.uploadBlobs(webApi, blobEntries, resp.missingBlobHashes, contentKey, migrateToVaultKey);for (const [hash, ciphertext] of retried.entries()) {uploadedCiphertexts.set(hash, ciphertext);}@@ -676,12 +715,21 @@ export class VaultSyncService {}await this.saveBlobCache(newCache);+ /*+ * KEK/VEK migration completed: cache the wrapped VEK for offline unlock and hand the new VEK to the caller,+ * which must adopt it as the session encryption key and re-encrypt the locally stored vault with it.+ */+ if (migrateToVaultKey && wrappedVek) {+ await storage.setItem(WRAPPED_VEK_STORAGE_KEY, wrappedVek);+ devLog('[V2Push] KEK/VEK migration complete: vault key created server-side, wrapped VEK cached locally.');+ }+const uploadedBlobChars = Array.from(uploadedCiphertexts.values()).reduce((sum, c) => sum + c.length, 0);const bucketChars = bucketDtos.reduce((sum, b) => sum + b.blob.length, 0);const totalChars = manifestCiphertext.length + bucketChars + uploadedBlobChars;devLog(`[V2Push] Total pushed (encrypted): manifest ${formatKb(manifestCiphertext.length)} + ${bucketDtos.length} buckets ${formatKb(bucketChars)} + ${uploadedCiphertexts.size} blobs ${formatKb(uploadedBlobChars)} = ${formatKb(totalChars)} (+ ${blobReferences.length} blob references).`);- return { status: 'ok', newManifestRevision: resp.newManifestRevision };+ return { status: 'ok', newManifestRevision: resp.newManifestRevision, newEncryptionKey: migrateToVaultKey ? contentKey : undefined };}/**@@ -730,9 +778,10 @@ export class VaultSyncService {* @param hashes - the subset of hashes to upload (hashes without an entry in `blobs` are skipped)* @param vek - symmetric encryption key* @param webApi - API client to reuse+ * @param overwrite - ask the server to replace the ciphertext of blobs it already has (KEK/VEK migration)* @returns Map of hash → uploaded ciphertext (base64), for the local encrypted blob cache.*/- private async uploadBlobs(webApi: WebApiService, blobs: Map<string, BlobEntry>, hashes: string[], vek: string): Promise<Map<string, string>> {+ private async uploadBlobs(webApi: WebApiService, blobs: Map<string, BlobEntry>, hashes: string[], vek: string, overwrite: boolean = false): Promise<Map<string, string>> {const ciphertexts = new Map<string, string>();if (hashes.length === 0) {return ciphertexts;@@ -752,7 +801,7 @@ export class VaultSyncService {if (batch.length > 0 && batchChars + ciphertext.length > BLOB_UPLOAD_BATCH_MAX_CHARS) {devLog(`[V2Push] Uploading blob batch: ${batch.length} blobs, ${formatKb(batchChars)}.`);- await webApi.post(BLOBS_UPLOAD_ENDPOINT, { blobs: batch });+ await webApi.post(BLOBS_UPLOAD_ENDPOINT, { blobs: batch, overwrite });batch = [];batchChars = 0;}@@ -763,7 +812,7 @@ export class VaultSyncService {if (batch.length > 0) {devLog(`[V2Push] Uploading blob batch: ${batch.length} blobs, ${formatKb(batchChars)}.`);- await webApi.post(BLOBS_UPLOAD_ENDPOINT, { blobs: batch });+ await webApi.post(BLOBS_UPLOAD_ENDPOINT, { blobs: batch, overwrite });}return ciphertexts;diff --git a/apps/browser-extension/src/utils/__tests__/EncryptionUtility.vek.test.ts b/apps/browser-extension/src/utils/__tests__/EncryptionUtility.vek.test.tsnew file mode 100644index 000000000..7b6492312--- /dev/null+++ b/apps/browser-extension/src/utils/__tests__/EncryptionUtility.vek.test.ts@@ -0,0 +1,61 @@+import { describe, it, expect } from 'vitest';++import EncryptionUtility from '@/utils/EncryptionUtility';++describe('EncryptionUtility VEK wrap/unwrap (KEK/VEK model)', () => {+ it('generates a 256-bit VEK as base64', () => {+ const vek = EncryptionUtility.generateVaultEncryptionKey();+ expect(Buffer.from(vek, 'base64').length).toBe(32);+ });++ it('generates a unique VEK per call', () => {+ expect(EncryptionUtility.generateVaultEncryptionKey()).not.toBe(EncryptionUtility.generateVaultEncryptionKey());+ });++ it('round-trips a VEK through wrap and unwrap with the same KEK', async () => {+ const vek = EncryptionUtility.generateVaultEncryptionKey();+ const kek = EncryptionUtility.generateVaultEncryptionKey();++ const wrapped = await EncryptionUtility.wrapVaultEncryptionKey(vek, kek);+ expect(wrapped).not.toBe(vek);+ // IV(12) + ciphertext(32) + tag(16) = 60 bytes.+ expect(Buffer.from(wrapped, 'base64').length).toBe(60);++ const unwrapped = await EncryptionUtility.unwrapVaultEncryptionKey(wrapped, kek);+ expect(unwrapped).toBe(vek);+ });++ it('produces a different wrapped VEK per wrap call (random IV)', async () => {+ const vek = EncryptionUtility.generateVaultEncryptionKey();+ const kek = EncryptionUtility.generateVaultEncryptionKey();+ expect(await EncryptionUtility.wrapVaultEncryptionKey(vek, kek)).not.toBe(await EncryptionUtility.wrapVaultEncryptionKey(vek, kek));+ });++ it('rejects unwrapping with a wrong KEK (AES-GCM auth failure doubles as password check)', async () => {+ const vek = EncryptionUtility.generateVaultEncryptionKey();+ const kek = EncryptionUtility.generateVaultEncryptionKey();+ const wrongKek = EncryptionUtility.generateVaultEncryptionKey();++ const wrapped = await EncryptionUtility.wrapVaultEncryptionKey(vek, kek);+ await expect(EncryptionUtility.unwrapVaultEncryptionKey(wrapped, wrongKek)).rejects.toThrow();+ });++ it('unwraps a rewrapped VEK after a simulated password change', async () => {+ const vek = EncryptionUtility.generateVaultEncryptionKey();+ const oldKek = EncryptionUtility.generateVaultEncryptionKey();+ const newKek = EncryptionUtility.generateVaultEncryptionKey();++ // Password change: unwrap with old KEK, rewrap with new KEK. The VEK itself must survive unchanged.+ const wrappedOld = await EncryptionUtility.wrapVaultEncryptionKey(vek, oldKek);+ const unwrapped = await EncryptionUtility.unwrapVaultEncryptionKey(wrappedOld, oldKek);+ const wrappedNew = await EncryptionUtility.wrapVaultEncryptionKey(unwrapped, newKek);++ expect(await EncryptionUtility.unwrapVaultEncryptionKey(wrappedNew, newKek)).toBe(vek);+ });++ it('encrypts and decrypts vault content with a VEK end-to-end', async () => {+ const vek = EncryptionUtility.generateVaultEncryptionKey();+ const ciphertext = await EncryptionUtility.symmetricEncrypt('vault-content', vek);+ expect(await EncryptionUtility.symmetricDecrypt(ciphertext, vek)).toBe('vault-content');+ });+});diff --git a/apps/browser-extension/src/utils/auth/SrpAuthService.ts b/apps/browser-extension/src/utils/auth/SrpAuthService.tsindex 9a7ea8fa4..eeed5c063 100644--- a/apps/browser-extension/src/utils/auth/SrpAuthService.ts+++ b/apps/browser-extension/src/utils/auth/SrpAuthService.ts@@ -22,6 +22,19 @@ export type RegisterRequest = {encryptionSettings: string;/** The SRP identity used for authentication (a random GUID generated at registration). */srpIdentity: string;+ /** The wrapped VEK (KEK/VEK model): base64 of the freshly generated VEK encrypted with the password-derived KEK. */+ wrappedVek: string;+};++/**+ * Prepared registration data: the request payload plus the key material the caller must keep client-side.+ */+export type PreparedRegistration = {+ request: RegisterRequest;+ /** The generated VEK (base64): the vault encryption key to store in session after successful registration. */+ vaultEncryptionKey: string;+ /** The password-derived key (base64): the KEK, only needed for wrapping/SRP, never for vault content. */+ derivedKey: string;};/**@@ -30,6 +43,10 @@ export type RegisterRequest = {export type RegistrationResult = {success: boolean;token?: TokenModel;+ /** The vault encryption key (VEK, base64) to use for all vault encryption after successful registration. */+ encryptionKey?: string;+ /** The wrapped VEK to cache locally for offline unlock. */+ wrappedVek?: string;error?: string;};@@ -282,12 +299,12 @@ export class SrpAuthService {** @param username - The username for registration* @param password - The password for registration- * @returns Registration request data ready to send to the API+ * @returns Registration request data ready to send to the API plus the generated key material*/public static async prepareRegistration(username: string,password: string- ): Promise<RegisterRequest> {+ ): Promise<PreparedRegistration> {const normalizedUsername = SrpAuthService.normalizeUsername(username);const salt = await SrpAuthService.generateSalt();@@ -309,13 +326,25 @@ export class SrpAuthService {const privateKey = await SrpAuthService.derivePrivateKey(salt, srpIdentity, credentials.passwordHashString);const verifier = await SrpAuthService.deriveVerifier(privateKey);+ /*+ * KEK/VEK: generate a random VEK that will encrypt the vault content, wrapped with the password-derived KEK.+ * The server stores only the wrapped form; the VEK itself stays client-side.+ */+ const vaultEncryptionKey = EncryptionUtility.generateVaultEncryptionKey();+ const wrappedVek = await EncryptionUtility.wrapVaultEncryptionKey(vaultEncryptionKey, credentials.passwordHashBase64);+return {- username: normalizedUsername,- salt,- verifier,- encryptionType: DEFAULT_ENCRYPTION.type,- encryptionSettings: DEFAULT_ENCRYPTION.settings,- srpIdentity,+ request: {+ username: normalizedUsername,+ salt,+ verifier,+ encryptionType: DEFAULT_ENCRYPTION.type,+ encryptionSettings: DEFAULT_ENCRYPTION.settings,+ srpIdentity,+ wrappedVek,+ },+ vaultEncryptionKey,+ derivedKey: credentials.passwordHashBase64,};}@@ -334,7 +363,7 @@ export class SrpAuthService {): Promise<RegistrationResult> {try {// Prepare registration data- const registerRequest = await SrpAuthService.prepareRegistration(username, password);+ const prepared = await SrpAuthService.prepareRegistration(username, password);// Normalize the API URLconst baseUrl = apiBaseUrl.replace(/\/$/, '') + '/v2/';@@ -345,7 +374,7 @@ export class SrpAuthService {headers: {'Content-Type': 'application/json',},- body: JSON.stringify(registerRequest),+ body: JSON.stringify(prepared.request),});if (!response.ok) {@@ -361,7 +390,7 @@ export class SrpAuthService {}const tokenModel = (await response.json()) as TokenModel;- return { success: true, token: tokenModel };+ return { success: true, token: tokenModel, encryptionKey: prepared.vaultEncryptionKey, wrappedVek: prepared.request.wrappedVek };} catch (error) {return {success: false,