Privacy-first password manager with built-in email aliasing. Fully encrypted and self-hostable.
Update unlockKey docs references (#2468)
Leendert de Borst72e277daa4e7
diff --git a/core/client/src/auth/MobileLoginService.ts b/core/client/src/auth/MobileLoginService.tsindex 68b6a27ef..665cfab14 100644--- a/core/client/src/auth/MobileLoginService.ts+++ b/core/client/src/auth/MobileLoginService.ts@@ -24,13 +24,13 @@ export function isMobileLoginErrorCode(value: unknown): value is MobileLoginErro}/**- * The decrypted session and unlock key of an approved mobile login.+ * The decrypted session and Account Key of an approved mobile login.*/export type MobileLoginResult = {username: string;token: string;refreshToken: string;- unlockKey: string;+ accountKey: string;salt: string;encryptionType: string;encryptionSettings: string;@@ -154,8 +154,8 @@ export class MobileLoginService {const privateKey = this.privateKey!;this.cleanup();- // The mobile app encrypted its stored key with our public key.- const unlockKey = bytesToBase64(await EncryptionUtility.decryptWithPrivateKeyObject(data.encryptedAccountKey, privateKey, MobileLoginProtocol.ACCOUNT_KEY_LABEL));+ // The mobile app encrypted its Account Key with our public key.+ const accountKey = bytesToBase64(await EncryptionUtility.decryptWithPrivateKeyObject(data.encryptedAccountKey, privateKey, MobileLoginProtocol.ACCOUNT_KEY_LABEL));// The server encrypted the session payload with a symmetric key, which is encrypted with our public key.const symmetricKey = bytesToBase64(await EncryptionUtility.decryptWithPrivateKeyObject(data.encryptedSymmetricKey, privateKey, MobileLoginProtocol.PAYLOAD_KEY_LABEL));@@ -165,7 +165,7 @@ export class MobileLoginService {username: payload.username,token: payload.token,refreshToken: payload.refreshToken,- unlockKey,+ accountKey,salt: payload.salt,encryptionType: payload.encryptionType,encryptionSettings: payload.encryptionSettings,diff --git a/core/client/src/auth/VaultKeyService.ts b/core/client/src/auth/VaultKeyService.tsindex ce36fac45..818c34a0c 100644--- a/core/client/src/auth/VaultKeyService.ts+++ b/core/client/src/auth/VaultKeyService.ts@@ -61,17 +61,17 @@ export class VaultKeyService {/*** Right after authentication: fetch the account's key chain from the server, check that the key opens it and* cache it for offline unlock.- * @param unlockKeyBase64 - the unlock key (the Argon2id output of the master password) or a stored Account Key+ * @param keyBase64 - the unlock key (the Argon2id output of the master password) or an Account Key* @param webApi - the API client to use* @returns The Account Key to store for this session.* @throws Error with {@link AppErrorCode.UNLOCK_KEY_REJECTED} when the key does not open the chain (wrong password).*/- public static async refreshKeyChain(unlockKeyBase64: string, webApi?: WebApiService): Promise<string> {+ public static async refreshKeyChain(keyBase64: string, webApi?: WebApiService): Promise<string> {const result = await VaultKeyService.fetchVaultKey(webApi);if (!result.supported) {// Older server: trust the local cache.- return VaultKeyService.verifyUnlockKey(unlockKeyBase64);+ return VaultKeyService.verifyUnlockKey(keyBase64);}if (!result.vaultKey) {@@ -80,21 +80,21 @@ export class VaultKeyService {throw new Error(formatErrorWithCode('The server holds no key chain for this account', AppErrorCode.KEY_OUT_OF_SYNC));}await getPlatform().storage.removeMany([StorageKeys.ENCRYPTED_VEK, StorageKeys.ENCRYPTED_ACCOUNT_KEY, StorageKeys.ACCOUNT_PUBLIC_KEY, StorageKeys.ENCRYPTED_ACCOUNT_PRIVATE_KEY, StorageKeys.SIGNING_PUBLIC_KEY, StorageKeys.ENCRYPTED_SIGNING_PRIVATE_KEY]);- return unlockKeyBase64;+ return keyBase64;}if (result.vaultKey.algorithm !== VaultKeyAlgorithm.Aes256Gcm) {throw new Error(formatErrorWithCode(`Unsupported Account Key algorithm '${result.vaultKey.algorithm}'`, AppErrorCode.VAULT_VERSION_INCOMPATIBLE));}- const keys = await VaultKeyService.openChain(unlockKeyBase64, result.vaultKey.encryptedAccountKey, result.vaultKey.encryptedVek ?? null, null);+ const keys = await VaultKeyService.openChain(keyBase64, result.vaultKey.encryptedAccountKey, result.vaultKey.encryptedVek ?? null, null);/** A device holding a vault under its unlock key but no chain yet (the account was upgraded on another device) stays* a legacy session: its first sync caches the chain and re-encrypts the stored vault under the VEK in one step.*/- if (keys.accountKey !== unlockKeyBase64 && !await VaultKeyService.hasLocalVaultKey() && await getPlatform().storage.get(StorageKeys.ENCRYPTED_VAULT) !== null) {- return unlockKeyBase64;+ if (keys.accountKey !== keyBase64 && !await VaultKeyService.hasLocalVaultKey() && await getPlatform().storage.get(StorageKeys.ENCRYPTED_VAULT) !== null) {+ return keyBase64;}await VaultKeyService.cacheVaultKeyBlobs(result.vaultKey);@@ -103,12 +103,12 @@ export class VaultKeyService {/*** Check offline that a key opens the locally cached chain (an account not yet upgraded has none; its key is the vault key).- * @param unlockKeyBase64 - the unlock key derived from the typed password, or a key restored by PIN or WebAuthn+ * @param keyBase64 - the unlock key derived from the typed password, or an Account Key restored by PIN or WebAuthn* @returns The Account Key to store for this session.* @throws Error with {@link AppErrorCode.UNLOCK_KEY_REJECTED} when the key does not open the chain (wrong password).*/- public static async verifyUnlockKey(unlockKeyBase64: string): Promise<string> {- return (await VaultKeyService.openKeyChain(unlockKeyBase64)).accountKey;+ public static async verifyUnlockKey(keyBase64: string): Promise<string> {+ return (await VaultKeyService.openKeyChain(keyBase64)).accountKey;}/**@@ -198,10 +198,10 @@ export class VaultKeyService {/*** Open the locally cached chain with a stored or typed key. Without a cached chain (account not yet upgraded) the* unlock key is the vault encryption key.- * @param unlockKeyBase64 - the Account Key or an unlock key+ * @param keyBase64 - the Account Key or an unlock key* @throws Error with {@link AppErrorCode.UNLOCK_KEY_REJECTED} when the key does not open the chain.*/- public static async openKeyChain(unlockKeyBase64: string): Promise<SessionKeys> {+ public static async openKeyChain(keyBase64: string): Promise<SessionKeys> {const storage = getPlatform().storage;const [encryptedAccountKey, encryptedVek, encryptedAccountPrivateKey] = await Promise.all([storage.get<string>(StorageKeys.ENCRYPTED_ACCOUNT_KEY),@@ -209,24 +209,24 @@ export class VaultKeyService {storage.get<string>(StorageKeys.ENCRYPTED_ACCOUNT_PRIVATE_KEY),]);if (!encryptedAccountKey) {- return { vaultEncryptionKey: unlockKeyBase64, accountPrivateKey: null, accountKey: unlockKeyBase64 };+ return { vaultEncryptionKey: keyBase64, accountPrivateKey: null, accountKey: keyBase64 };}- return VaultKeyService.openChain(unlockKeyBase64, encryptedAccountKey, encryptedVek, encryptedAccountPrivateKey);+ return VaultKeyService.openChain(keyBase64, encryptedAccountKey, encryptedVek, encryptedAccountPrivateKey);}/*** Walk a chain with the Account Key or an unlock key (see the Rust `open_account_key_chain`).- * @param unlockKeyBase64 - the Account Key or an unlock key+ * @param keyBase64 - the Account Key or an unlock key* @param encryptedAccountKey - the Account Key encrypted with the KEK derived from the unlock key* @param encryptedVek - the VEK encrypted with the Account Key* @param encryptedAccountPrivateKey - the account private key encrypted with the Account Key, or null when the account has none yet*/- private static async openChain(unlockKeyBase64: string, encryptedAccountKey: string, encryptedVek: string | null, encryptedAccountPrivateKey: string | null): Promise<SessionKeys> {+ private static async openChain(keyBase64: string, encryptedAccountKey: string, encryptedVek: string | null, encryptedAccountPrivateKey: string | null): Promise<SessionKeys> {if (!encryptedVek) {throw new Error('Vault key chain is missing the encrypted VEK');}- const opened = await openAccountKeyChain(unlockKeyBase64, encryptedAccountKey, encryptedVek, encryptedAccountPrivateKey);+ const opened = await openAccountKeyChain(keyBase64, encryptedAccountKey, encryptedVek, encryptedAccountPrivateKey);switch (opened.status) {case 'opened':return { vaultEncryptionKey: opened.vaultEncryptionKey, accountPrivateKey: opened.accountPrivateKey, accountKey: opened.accountKey };diff --git a/core/client/src/constants/StorageKeys.ts b/core/client/src/constants/StorageKeys.tsindex dd86a5fad..2da2b4d60 100644--- a/core/client/src/constants/StorageKeys.ts+++ b/core/client/src/constants/StorageKeys.ts@@ -43,7 +43,7 @@ export const StorageKeys = {PRIVATE_EMAIL_DOMAINS: 'local:privateEmailDomains',/** Private email domains that are hidden from the domain picker. */HIDDEN_PRIVATE_EMAIL_DOMAINS: 'local:hiddenPrivateEmailDomains',- /** Argon2 parameters used to derive the unlock key from the master password. */+ /** Argon2 parameters used to derive the unlock key from the master password (the storage key string name is historical). */UNLOCK_KEY_DERIVATION_PARAMS: 'local:encryptionKeyDerivationParams',/** The VEK encrypted with the Account Key, as returned by the server. */ENCRYPTED_VEK: 'local:encryptedVek',@@ -99,6 +99,7 @@ export const StorageKeys = {/*** The Account Key of the session, from which the vault encryption key and account private key are opened on demand (see VaultKeyService).* Session-only: it must never persist to disk. An additional unlock method (PIN) protects this same key.+ * The `unlockKey` in the storage key string is historical; the value is the Account Key.*/ACCOUNT_KEY: 'session:unlockKey',/** The sync hold record (reason + when it was taken) while an operation no sync may race runs; see VaultSyncHold. */@@ -119,7 +120,7 @@ export const AUTH_STORAGE_KEYS: readonly StorageKey[] = [StorageKeys.CAPABILITIES,];-/** Keys that must not survive a vault lock: the unlock key. Hosts add anything they derive from decrypted data. */+/** Keys that must not survive a vault lock: the Account Key. Hosts add anything they derive from decrypted data. */export const VAULT_LOCK_STORAGE_KEYS: readonly StorageKey[] = [StorageKeys.ACCOUNT_KEY,];diff --git a/core/client/src/crypto/EncryptionUtility.ts b/core/client/src/crypto/EncryptionUtility.tsindex 9db03ea40..326dcb13f 100644--- a/core/client/src/crypto/EncryptionUtility.ts+++ b/core/client/src/crypto/EncryptionUtility.ts@@ -2,6 +2,9 @@ import { argon2DeriveKey } from '../rust/RustCore';import { base64ToBytes, bytesToBase64 } from '../utilities/Base64';import { logDefect } from '../utilities/Diagnostics';+/** AES-GCM IV length in bytes; every AES-GCM payload starts with it. */+const AES_GCM_IV_LENGTH = 12;+/*** Utility class for encryption operations including:* - Argon2Id key derivation@@ -26,64 +29,23 @@ export class EncryptionUtility {}/**- * Encrypts data using AES-GCM symmetric encryption+ * Encrypts a UTF-8 string with AES-256-GCM into base64 `IV | ciphertext | tag`. An empty string stays empty.*/public static async symmetricEncrypt(plaintext: string, base64Key: string): Promise<string> {if (!plaintext) {return plaintext;}- const key = await crypto.subtle.importKey(- "raw",- base64ToBytes(base64Key),- {- name: "AES-GCM",- length: 256,- },- false,- ["encrypt"]- );-- const iv = crypto.getRandomValues(new Uint8Array(12));- const encoder = new TextEncoder();- const encoded = encoder.encode(plaintext);-- const ciphertext = await crypto.subtle.encrypt(- { name: "AES-GCM", iv: iv },- key,- encoded- );-- const combined = new Uint8Array(iv.length + ciphertext.byteLength);- combined.set(iv, 0);- combined.set(new Uint8Array(ciphertext), iv.length);-- return bytesToBase64(combined);+ return EncryptionUtility.symmetricEncryptBytes(new TextEncoder().encode(plaintext), base64Key);}/**- * Encrypts raw bytes using AES-GCM symmetric encryption.+ * Encrypts bytes with AES-256-GCM (random 12-byte IV, no AAD) into base64 `IV | ciphertext | tag`.*/public static async symmetricEncryptBytes(plaintextBytes: Uint8Array, base64Key: string): Promise<string> {- const key = await crypto.subtle.importKey(- "raw",- base64ToBytes(base64Key),- {- name: "AES-GCM",- length: 256,- },- false,- ["encrypt"]- );-- const iv = crypto.getRandomValues(new Uint8Array(12));-- // WebCrypto accepts any Uint8Array at runtime; the cast satisfies the ArrayBuffer-only BufferSource typing.- const ciphertext = await crypto.subtle.encrypt(- { name: "AES-GCM", iv: iv },- key,- plaintextBytes as Uint8Array<ArrayBuffer>- );+ const key = await EncryptionUtility.importAesKey(base64Key, 'encrypt');+ const iv = crypto.getRandomValues(new Uint8Array(AES_GCM_IV_LENGTH));+ const ciphertext = await crypto.subtle.encrypt({ name: 'AES-GCM', iv }, key, plaintextBytes as Uint8Array<ArrayBuffer>);const combined = new Uint8Array(iv.length + ciphertext.byteLength);combined.set(iv, 0);@@ -93,115 +55,50 @@ export class EncryptionUtility {}/**- * Decrypts data using AES-GCM symmetric encryption+ * Decrypts base64 `IV | ciphertext | tag` with AES-256-GCM into a UTF-8 string.*/public static async symmetricDecrypt(base64Ciphertext: string, base64Key: string): Promise<string> {if (!base64Ciphertext) {return base64Ciphertext;}- const key = await crypto.subtle.importKey(- "raw",- base64ToBytes(base64Key),- {- name: "AES-GCM",- length: 256,- },- false,- ["decrypt"]- );-- const ivAndCiphertext = base64ToBytes(base64Ciphertext);- const iv = ivAndCiphertext.slice(0, 12);- const ciphertext = ivAndCiphertext.slice(12);-- const decrypted = await crypto.subtle.decrypt(- { name: "AES-GCM", iv: iv },- key,- ciphertext- );-- const decoder = new TextDecoder();- return decoder.decode(decrypted);+ return new TextDecoder().decode(await EncryptionUtility.symmetricDecryptBytes(base64ToBytes(base64Ciphertext), base64Key));}/**- * Decrypts data using AES-GCM symmetric encryption with raw bytes input/output+ * Decrypts `IV | ciphertext | tag` bytes with AES-256-GCM (no AAD).*/public static async symmetricDecryptBytes(encryptedBytes: Uint8Array, base64Key: string): Promise<Uint8Array> {if (!encryptedBytes || encryptedBytes.length === 0) {return encryptedBytes;}- const key = await crypto.subtle.importKey(- "raw",- base64ToBytes(base64Key),- {- name: "AES-GCM",- length: 256,- },- false,- ["decrypt"]- );+ const key = await EncryptionUtility.importAesKey(base64Key, 'decrypt');+ const iv = encryptedBytes.slice(0, AES_GCM_IV_LENGTH);+ const ciphertext = encryptedBytes.slice(AES_GCM_IV_LENGTH);- const iv = encryptedBytes.slice(0, 12);- const ciphertext = encryptedBytes.slice(12);-- const decrypted = await crypto.subtle.decrypt(- { name: "AES-GCM", iv },- key,- ciphertext- );-- return new Uint8Array(decrypted);+ return new Uint8Array(await crypto.subtle.decrypt({ name: 'AES-GCM', iv }, key, ciphertext));}/**- * Generates a new RSA key pair for asymmetric encryption+ * Generates an extractable RSA-OAEP-2048 (SHA-256) key pair, both halves exported as JWK strings.*/public static async generateRsaKeyPair(): Promise<{ publicKey: string, privateKey: string }> {- const keyPair = await crypto.subtle.generateKey(- {- name: "RSA-OAEP",- modulusLength: 2048,- publicExponent: new Uint8Array([1, 0, 1]),- hash: "SHA-256",- },- true,- ["encrypt", "decrypt"]- );+ const keyPair = await EncryptionUtility.generateRsaOaepKeyPair(true);+ const publicKey = await crypto.subtle.exportKey('jwk', keyPair.publicKey);+ const privateKey = await crypto.subtle.exportKey('jwk', keyPair.privateKey);- const publicKey = await crypto.subtle.exportKey("jwk", keyPair.publicKey);- const privateKey = await crypto.subtle.exportKey("jwk", keyPair.privateKey);-- return {- publicKey: JSON.stringify(publicKey),- privateKey: JSON.stringify(privateKey)- };+ return { publicKey: JSON.stringify(publicKey), privateKey: JSON.stringify(privateKey) };}/**- * Generates a new RSA key pair with a non-extractable private key- * Private key stays inside WebCrypto and public key is returned as JWK string for transport+ * Generates an RSA-OAEP-2048 (SHA-256) key pair whose private key stays inside WebCrypto; the public key is a JWK string.*/public static async generateRsaKeyPairNonExtractable(): Promise<{ publicKeyJwk: string, privateKey: CryptoKey }> {- const keyPair = await crypto.subtle.generateKey(- {- name: "RSA-OAEP",- modulusLength: 2048,- publicExponent: new Uint8Array([1, 0, 1]),- hash: "SHA-256",- },- false,- ["encrypt", "decrypt"]- );+ const keyPair = await EncryptionUtility.generateRsaOaepKeyPair(false);+ const publicKey = await crypto.subtle.exportKey('jwk', keyPair.publicKey);- const publicKey = await crypto.subtle.exportKey("jwk", keyPair.publicKey);-- return {- publicKeyJwk: JSON.stringify(publicKey),- privateKey: keyPair.privateKey,- };+ return { publicKeyJwk: JSON.stringify(publicKey), privateKey: keyPair.privateKey };}/**@@ -233,18 +130,27 @@ export class EncryptionUtility {}/**- * Imports an RSA-OAEP private key as non-extractable.+ * Imports a JWK RSA-OAEP (SHA-256) private key as a non-extractable decrypt-only CryptoKey.+ */+ public static async importPrivateKey(privateKey: string): Promise<CryptoKey> {+ return await crypto.subtle.importKey('jwk', JSON.parse(privateKey), { name: 'RSA-OAEP', hash: 'SHA-256' }, false, ['decrypt']);+ }++ /**+ * Imports a raw 256-bit AES-GCM key for a single usage.+ */+ private static async importAesKey(base64Key: string, usage: 'encrypt' | 'decrypt'): Promise<CryptoKey> {+ return await crypto.subtle.importKey('raw', base64ToBytes(base64Key), { name: 'AES-GCM', length: 256 }, false, [usage]);+ }++ /**+ * Generates an RSA-OAEP-2048 key pair with SHA-256 and exponent 65537.*/- private static async importPrivateKey(privateKey: string): Promise<CryptoKey> {- return await crypto.subtle.importKey(- "jwk",- JSON.parse(privateKey),- {- name: "RSA-OAEP",- hash: "SHA-256",- },- false,- ["decrypt"]+ private static async generateRsaOaepKeyPair(extractable: boolean): Promise<CryptoKeyPair> {+ return await crypto.subtle.generateKey(+ { name: 'RSA-OAEP', modulusLength: 2048, publicExponent: new Uint8Array([1, 0, 1]), hash: 'SHA-256' },+ extractable,+ ['encrypt', 'decrypt']);}}diff --git a/core/client/src/email/EmailDecryption.ts b/core/client/src/email/EmailDecryption.tsindex 3d9befef5..7ef82beea 100644--- a/core/client/src/email/EmailDecryption.ts+++ b/core/client/src/email/EmailDecryption.ts@@ -10,6 +10,7 @@* core compiled to WebAssembly for RSA and for large sources. The mobile app has no WebCrypto and uses the native Rust* core (core/rust/src/crypto) instead. Both produce and read the same formats.*/+import { EncryptionUtility } from '../crypto/EncryptionUtility';import { devWarn } from '../platform/Logger';import { parseEmailSource, rustCore, type ParsedEmailAttachment } from '../rust/RustCore';import { base64ToBytes, bytesToBase64 } from '../utilities/Base64';@@ -157,12 +158,12 @@ async function unwrapSymmetricKey(encryptedSymmetricKey: string, encryptionKey:let privateKey = privateKeyCache.get(encryptionKey.PublicKey);if (!privateKey) {- privateKey = crypto.subtle.importKey('jwk', JSON.parse(encryptionKey.PrivateKey), { name: 'RSA-OAEP', hash: 'SHA-256' }, false, ['decrypt']);+ privateKey = EncryptionUtility.importPrivateKey(encryptionKey.PrivateKey);privateKey.catch(() => privateKeyCache.delete(encryptionKey.PublicKey));privateKeyCache.set(encryptionKey.PublicKey, privateKey);}- return bytesToBase64(new Uint8Array(await crypto.subtle.decrypt({ name: 'RSA-OAEP' }, await privateKey, base64ToBytes(encryptedSymmetricKey))));+ return bytesToBase64(await EncryptionUtility.decryptWithPrivateKeyObject(encryptedSymmetricKey, await privateKey));}/**@@ -192,6 +193,5 @@ async function decryptBytes(encrypted: Uint8Array, symmetricKey: string): Promisreturn rustCore().symmetricDecryptBytes(encrypted, symmetricKey);}- const key = await crypto.subtle.importKey('raw', base64ToBytes(symmetricKey), { name: 'AES-GCM', length: 256 }, false, ['decrypt']);- return new Uint8Array(await crypto.subtle.decrypt({ name: 'AES-GCM', iv: encrypted.slice(0, 12) }, key, encrypted.slice(12)));+ return EncryptionUtility.symmetricDecryptBytes(encrypted, symmetricKey);}