Privacy-first password manager with built-in email aliasing. Fully encrypted and self-hostable.
Update encryption key naming in browser extension (#2159)
Leendert de Borst43c169ea3f9e
diff --git a/apps/browser-extension/src/entrypoints/background/VaultMessageHandler.ts b/apps/browser-extension/src/entrypoints/background/VaultMessageHandler.tsindex 23cc8e44f..86cac5a9a 100644--- a/apps/browser-extension/src/entrypoints/background/VaultMessageHandler.ts+++ b/apps/browser-extension/src/entrypoints/background/VaultMessageHandler.ts@@ -429,7 +429,7 @@ export async function handleClearVaultData(): Promise<messageBoolResponse> {// Clear vault data and every piece of state derived from it (sync bookkeeping, dirty flags, bucket revisions)await storage.removeItems(allVaultDataStorageKeys());- // Clear the cached vault key and wrapped VEK.+ // Clear the cached vault key and encrypted VEK.VaultKeyService.clearCache();// Clear all local preferences (site settings, login save settings, etc.)@@ -1352,9 +1352,9 @@ export async function handleGetServerRevision(): Promise<number> {/*** Adopt a server-side vault key this device does not know about yet.*- * A missing local wrapped-VEK cache means one of two things: this user is genuinely still legacy (their next full+ * A missing local encrypted-VEK cache means one of two things: this user is genuinely still legacy (their next full* push performs the KEK/VEK migration), or another device migrated while this one held the old password-derived key.- * Every path that adopts a VEK as the session key writes the wrapped-VEK cache first, so a session key that is+ * Every path that adopts a VEK as the session key writes the encrypted-VEK cache first, so a session key that is* already the VEK without a cache is not a reachable state -- it can only come from torn storage, which a re-login fixes.** TODO: this method can be removed once all users have migrated to the KEK/VEK model and we don't support legacy users anymore.@@ -1388,11 +1388,11 @@ async function adoptRemoteVaultKeyIfNeeded(): Promise<boolean> {return true;}- const serverWrappedVek = fetchResult.vaultKey.wrappedVek;+ const serverEncryptedVek = fetchResult.vaultKey.encryptedVek;const encryptedVault = await storage.getItem(StorageKeys.ENCRYPTED_VAULT) as string | null;try {- const vek = await EncryptionUtility.unwrapVaultEncryptionKey(serverWrappedVek, sessionKey);+ const vek = await EncryptionUtility.unwrapVaultEncryptionKey(serverEncryptedVek, sessionKey);// The session key was the KEK: re-encrypt the locally persisted vault with the VEK before swapping the session key.if (encryptedVault) {@@ -1400,7 +1400,7 @@ async function adoptRemoteVaultKeyIfNeeded(): Promise<boolean> {await storage.setItem(StorageKeys.ENCRYPTED_VAULT, await EncryptionUtility.symmetricEncrypt(decrypted, vek));}- await storage.setItem(StorageKeys.WRAPPED_VEK, serverWrappedVek);+ await storage.setItem(StorageKeys.ENCRYPTED_VEK, serverEncryptedVek);await handleStoreEncryptionKey(vek);cachedSqliteClient = null;cachedVaultBlob = null;diff --git a/apps/browser-extension/src/utils/EncryptionUtility.ts b/apps/browser-extension/src/utils/EncryptionUtility.tsindex a98c2e1bb..6f4107d47 100644--- a/apps/browser-extension/src/utils/EncryptionUtility.ts+++ b/apps/browser-extension/src/utils/EncryptionUtility.ts@@ -2,6 +2,7 @@ import { Buffer } from 'buffer';import argon2 from 'argon2-browser/dist/argon2-bundled.min.js';+import { devWarn } from '@/utils/devLogger/DevLogger';import type { EncryptionKey } from '@/utils/dist/core/models/vault';import type { Email, MailboxEmail } from '@/utils/dist/core/models/webapi';@@ -204,10 +205,10 @@ export class EncryptionUtility {}/**- * Unwraps (decrypts) a wrapped VEK with a KEK. Returns the VEK as base64.+ * Unwraps (decrypts) an encrypted 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));+ public static async unwrapVaultEncryptionKey(encryptedVekBase64: string, kekBase64: string): Promise<string> {+ const wrappedBytes = Uint8Array.from(atob(encryptedVekBase64), c => c.charCodeAt(0));const vekBytes = await this.symmetricDecryptBytes(wrappedBytes, kekBase64);return btoa(String.fromCharCode(...vekBytes));}@@ -408,12 +409,16 @@ export class EncryptionUtility {/*** Decrypts a list of emails based on the provided public/private key pairs.+ *+ * Emails that cannot be decrypted are skipped rather than failing the batch. The server only serves mail the+ * caller holds a key for, so this should not happen but we handle it gracefully to prevent one unreadable record+ * from breaking the whole list view.*/public static async decryptEmailList(emails: MailboxEmail[],encryptionKeys: EncryptionKey[]): Promise<MailboxEmail[]> {- return Promise.all(emails.map(async email => {+ const results = await Promise.all(emails.map(async email => {try {const encryptionKey = encryptionKeys.find(key => key.PublicKey === email.encryptionKey);@@ -444,9 +449,12 @@ export class EncryptionUtility {return decryptedEmail;} catch (err) {- throw new Error(err instanceof Error ? err.message : 'Failed to decrypt email');+ devWarn(`[Email] Skipping email ${email.id}, it could not be decrypted:`, err);+ return null;}}));++ return results.filter((email): email is MailboxEmail => email !== null);}/**diff --git a/apps/browser-extension/src/utils/VaultSyncService.ts b/apps/browser-extension/src/utils/VaultSyncService.tsindex d1a9c5a84..ef4f5b547 100644--- a/apps/browser-extension/src/utils/VaultSyncService.ts+++ b/apps/browser-extension/src/utils/VaultSyncService.ts@@ -145,12 +145,12 @@ type ManifestDto = {name?: string | null;/** Username of the manifest owner; set only on manifests granted to the caller by another user. */ownerUsername?: string | null;- /** The manifest VEK wrapped with the caller's public key; set only on manifests granted by another user. */- wrappedVek?: string | null;- /** Wrap scheme of `wrappedVek` (e.g. "rsa-oaep"). */- wrapScheme?: string | null;- /** The public key `wrappedVek` was wrapped with. Selects which of the caller's keypairs unwraps the grant. */- wrapPublicKey?: string | null;+ /** The manifest VEK encrypted with the caller's public key; set only on manifests granted by another user. */+ encryptedVek?: string | null;+ /** Algorithm of `encryptedVek` (e.g. "rsa-oaep-sha256"). */+ algorithm?: string | null;+ /** The public key `encryptedVek` was encrypted with. Selects which of the caller's keypairs decrypts the grant. */+ encryptionPublicKey?: string | null;};/** A data bucket as carried in the GET snapshot / bundled upload. `category` matches the server enum name (e.g. "Settings"). */@@ -209,10 +209,10 @@ type ManifestWriteDto = {credentialsCount: number;blobReferences: BlobRefDto[];/**- * The newly generated VEK wrapped with the password-derived KEK. Set on the root write of a legacy user's first manifest-v1 push.+ * The newly generated VEK encrypted with the password-derived KEK. Set on the root write of a legacy user's first manifest-v1 push.* TODO: can be deleted once all users have migrated to manifest-v1.*/- wrappedVek?: string;+ encryptedVek?: string;};/** Per-manifest result of a write: the new revision (Ok) or the current server revision (Outdated). */@@ -430,7 +430,7 @@ export class VaultSyncService {}/*- * Resolve every non-root (shared-folder) manifest in the snapshot. The snapshot carries the folder VEK wrapped with the user's public key.+ * Resolve every non-root (shared-folder) manifest in the snapshot. The snapshot carries the folder VEK encrypted with the user's public key.* Unwrap it with the private key, read from the small EncryptionKeys data bucket. A manifest whose key can't be resolved is skipped.*/const sharedManifestDtos = (snapshot.manifests ?? []).filter(m => !m.isRoot && m.blob);@@ -439,16 +439,16 @@ export class VaultSyncService {const encryptionKeysBucket = dataBuckets.find(b => b.category === VaultDataBucketCategory.EncryptionKeys) ?? null;for (const dto of sharedManifestDtos) {let vek: string | null = null;- if (dto.wrappedVek && dto.wrapPublicKey) {+ if (dto.encryptedVek && dto.encryptionPublicKey) {/*- * Each grant was wrapped for a specific public key; select the matching private key so a grant wrapped- * before a key rotation still unwraps (the current primary is never assumed). A grant without a wrap- * public key can't be resolved, so it falls through and the manifest is skipped below.+ * Each grant was encrypted for a specific public key; select the matching private key so a grant encrypted+ * before a key rotation still decrypts (the current primary is never assumed). A grant without an encryption+ * public key cannot be resolved, so it falls through and the manifest is skipped below.*/- const privateKeyJwk = await this.resolvePrivateKeyJwk(encryptionKeysBucket, dto.wrapPublicKey);+ const privateKeyJwk = await this.resolvePrivateKeyJwk(encryptionKeysBucket, dto.encryptionPublicKey);if (privateKeyJwk) {try {- vek = await SharingService.unwrapFolderVek(dto.wrappedVek, privateKeyJwk);+ vek = await SharingService.unwrapFolderVek(dto.encryptedVek, privateKeyJwk);} catch (e) {devWarn(`[V2Pull] Failed to unwrap VEK of shared manifest ${dto.manifestId}, skipping it.`, e);}@@ -595,16 +595,16 @@ export class VaultSyncService {/*** Resolve the user's asymmetric private key (JWK string) for unwrapping a shared-folder VEK. The keypair lives* in the small EncryptionKeys data bucket, decryptable on its own without materializing the root manifest. The- * keypair matching `wrapPublicKey` is selected, so a grant wrapped before a key rotation still unwraps even+ * keypair matching `encryptionPublicKey` is selected, so a grant encrypted before a key rotation still decrypts even* though that key is no longer primary. Returns null when no matching key is available.* @param encryptionKeysBucket - the decrypted EncryptionKeys data bucket, or null when absent- * @param wrapPublicKey - the public key the grant's VEK was wrapped with+ * @param encryptionPublicKey - the public key the grant's VEK was encrypted with*/- private async resolvePrivateKeyJwk(encryptionKeysBucket: VaultDataBucket | null, wrapPublicKey: string): Promise<string | null> {+ private async resolvePrivateKeyJwk(encryptionKeysBucket: VaultDataBucket | null, encryptionPublicKey: string): Promise<string | null> {if (!encryptionKeysBucket) {return null;}- const keyRow = await vaultCodecExtractEncryptionKeyForPublicKeyFromBucket(encryptionKeysBucket, wrapPublicKey);+ const keyRow = await vaultCodecExtractEncryptionKeyForPublicKeyFromBucket(encryptionKeysBucket, encryptionPublicKey);return typeof keyRow?.PrivateKey === 'string' ? keyRow.PrivateKey : null;}@@ -687,7 +687,7 @@ export class VaultSyncService {*/const migrateToVaultKey = options?.createVaultKey === true;const contentKey = migrateToVaultKey ? EncryptionUtility.generateVaultEncryptionKey() : vek;- const wrappedVek = migrateToVaultKey ? await EncryptionUtility.wrapVaultEncryptionKey(contentKey, vek) : null;+ const encryptedVek = 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.');}@@ -910,7 +910,7 @@ export class VaultSyncService {* Set only on the KEK/VEK migration push, where the server creates the vault key alongside this root revision.* A migration always forces a root write (see writeRoot), so the key can never be stranded without one.*/- ...(wrappedVek ? { wrappedVek } : {}),+ ...(encryptedVek ? { encryptedVek } : {}),}] : []),...sharedManifestWrites,];@@ -1015,12 +1015,12 @@ 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,+ * KEK/VEK migration completed: cache the encrypted 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(StorageKeys.WRAPPED_VEK, wrappedVek);- devLog('[V2Push] KEK/VEK migration complete: vault key created server-side, wrapped VEK cached locally.');+ if (migrateToVaultKey && encryptedVek) {+ await storage.setItem(StorageKeys.ENCRYPTED_VEK, encryptedVek);+ devLog('[V2Push] KEK/VEK migration complete: vault key created server-side, encrypted VEK cached locally.');}const uploadedBlobChars = Array.from(uploadedCiphertexts.values()).reduce((sum, c) => sum + c.length, 0);diff --git a/apps/browser-extension/src/utils/__tests__/EncryptionUtility.crypto.test.ts b/apps/browser-extension/src/utils/__tests__/EncryptionUtility.crypto.test.tsindex a3f608839..d8c3d1f92 100644--- a/apps/browser-extension/src/utils/__tests__/EncryptionUtility.crypto.test.ts+++ b/apps/browser-extension/src/utils/__tests__/EncryptionUtility.crypto.test.ts@@ -196,6 +196,38 @@ describe('email RSA private key cache', () => {}});+ it('skips undecryptable emails instead of failing the whole batch', async () => {+ /*+ * A mailbox can legitimately contain a message this user has no key for — mail delivered to an alias before+ * it moved into a shared folder is encrypted with the owner's personal key. The server filters those out,+ * but if one slips through it must cost that single row, not blank the entire mailbox.+ */+ const keyPair = await EncryptionUtility.generateRsaKeyPair();+ const strangerKeyPair = await EncryptionUtility.generateRsaKeyPair();+ const encryptionKey: EncryptionKey = {+ Id: 'key-a',+ PublicKey: keyPair.publicKey,+ PrivateKey: keyPair.privateKey,+ IsPrimary: true,+ };+ const strangerKey: EncryptionKey = {+ Id: 'key-stranger',+ PublicKey: strangerKeyPair.publicKey,+ PrivateKey: strangerKeyPair.privateKey,+ IsPrimary: false,+ };+ const emails = [+ await createMailboxEmail(1, encryptionKey, '0123456789abcdef0123456789abcdef', 'Readable'),+ await createMailboxEmail(2, strangerKey, 'abcdef0123456789abcdef0123456789', 'Unreadable'),+ await createMailboxEmail(3, encryptionKey, 'fedcba9876543210fedcba9876543210', 'Also readable'),+ ];++ // Only the own key is held, so email 2 cannot be decrypted.+ const decryptedEmails = await EncryptionUtility.decryptEmailList(emails, [encryptionKey]);++ expect(decryptedEmails.map(email => email.subject)).toEqual(['Readable', 'Also readable']);+ });+it('reuses cached private keys when decrypting attachments', async () => {const keyPair = await EncryptionUtility.generateRsaKeyPair();const encryptionKey: EncryptionKey = {diff --git a/apps/browser-extension/src/utils/auth/SrpAuthService.ts b/apps/browser-extension/src/utils/auth/SrpAuthService.tsindex eeed5c063..15d8dfc5f 100644--- a/apps/browser-extension/src/utils/auth/SrpAuthService.ts+++ b/apps/browser-extension/src/utils/auth/SrpAuthService.ts@@ -22,8 +22,8 @@ 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;+ /** The encrypted VEK (KEK/VEK model): base64 of the freshly generated VEK encrypted with the password-derived KEK. */+ encryptedVek: string;};/**@@ -45,8 +45,8 @@ export type RegistrationResult = {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;+ /** The encrypted VEK to cache locally for offline unlock. */+ encryptedVek?: string;error?: string;};@@ -327,11 +327,11 @@ export class SrpAuthService {const verifier = await SrpAuthService.deriveVerifier(privateKey);/*- * KEK/VEK: generate a random VEK that will encrypt the vault content, wrapped with the password-derived KEK.+ * KEK/VEK: generate a random VEK that will encrypt the vault content, encrypted 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);+ const encryptedVek = await EncryptionUtility.wrapVaultEncryptionKey(vaultEncryptionKey, credentials.passwordHashBase64);return {request: {@@ -341,7 +341,7 @@ export class SrpAuthService {encryptionType: DEFAULT_ENCRYPTION.type,encryptionSettings: DEFAULT_ENCRYPTION.settings,srpIdentity,- wrappedVek,+ encryptedVek,},vaultEncryptionKey,derivedKey: credentials.passwordHashBase64,@@ -390,7 +390,7 @@ export class SrpAuthService {}const tokenModel = (await response.json()) as TokenModel;- return { success: true, token: tokenModel, encryptionKey: prepared.vaultEncryptionKey, wrappedVek: prepared.request.wrappedVek };+ return { success: true, token: tokenModel, encryptionKey: prepared.vaultEncryptionKey, encryptedVek: prepared.request.encryptedVek };} catch (error) {return {success: false,diff --git a/apps/browser-extension/src/utils/constants/storageKeys.ts b/apps/browser-extension/src/utils/constants/storageKeys.tsindex 79b77ac8b..5fcc72511 100644--- a/apps/browser-extension/src/utils/constants/storageKeys.ts+++ b/apps/browser-extension/src/utils/constants/storageKeys.ts@@ -44,8 +44,8 @@ export const StorageKeys = {HIDDEN_PRIVATE_EMAIL_DOMAINS: 'local:hiddenPrivateEmailDomains',/** Argon2 parameters used to derive the KEK from the master password. */ENCRYPTION_KEY_DERIVATION_PARAMS: 'local:encryptionKeyDerivationParams',- /** The VEK wrapped with the KEK, as returned by the server. */- WRAPPED_VEK: 'local:wrappedVek',+ /** The VEK encrypted with the KEK, as returned by the server. */+ ENCRYPTED_VEK: 'local:encryptedVek',/** -- Sync state --@@ -268,7 +268,7 @@ export const allVaultDataStorageKeys = (): StorageKey[] => [StorageKeys.MUTATION_SEQUENCE,StorageKeys.IS_OFFLINE_MODE,StorageKeys.ENCRYPTION_KEY_DERIVATION_PARAMS,- StorageKeys.WRAPPED_VEK,+ StorageKeys.ENCRYPTED_VEK,StorageKeys.USERNAME,...ALL_VAULT_MUTATION_SCOPES.map(scope => dirtyScopeStorageKey(scope)),...ALL_VAULT_BUCKET_SCOPES.map(category => bucketRevisionStorageKey(category)),