Privacy-first password manager with built-in email aliasing. Fully encrypted and self-hostable.
Update unlock scaffolding logic (#2469)
Leendert de Borstf76ec0e03118
diff --git a/apps/browser-extension/src/entrypoints/background/AuthHandler.ts b/apps/browser-extension/src/entrypoints/background/AuthHandler.tsindex 5612925c1..d4e3bdd7b 100644--- a/apps/browser-extension/src/entrypoints/background/AuthHandler.ts+++ b/apps/browser-extension/src/entrypoints/background/AuthHandler.ts@@ -13,6 +13,7 @@ import { handleClearSession, handleFullVaultSync, handleGetUnlockKeyDerivationPaimport { StorageKeys } from '@/utils/constants/storageKeys';import { logExpected, logFailure } from '@/utils/Diagnostics';+import { convertLegacyPinKey } from '@/utils/LegacyKeyConversion';import { LocalPreferencesService } from '@/utils/LocalPreferencesService';import { sendMessage } from '@/utils/messaging/ExtensionMessaging';import { IncorrectPinError, InvalidPinFormatError, PinLockedError, resetFailedAttempts, unlockWithPin } from '@/utils/PinUnlockService';@@ -115,7 +116,7 @@ async function checkServerStatus(webApi: WebApiService): Promise<{ online: boole}/**- * Store the checked unlock key, which unlocks the vault, and tell content scripts about it.+ * Store the checked key (see VaultKeyService.SessionKeys.accountKey), which unlocks the vault, and tell content scripts about it.*/async function storeUnlockKey(unlockKey: string, offline: boolean, broadcast: boolean): Promise<void> {const stored = await handleStoreUnlockKey(unlockKey);@@ -146,12 +147,11 @@ export function handleUnlockWithPassword(data: { password: string }): Promise<Baif (status.online) {const username = await storage.getItem<string>(StorageKeys.USERNAME);const loginResponse = await new SrpLoginService(webApi).initiateLogin(username!);- const credentials = await SrpAuthService.prepareCredentials(data.password, loginResponse.salt, loginResponse.encryptionSettings);+ const credentials = await SrpAuthService.prepareCredentials(data.password, loginResponse.salt, loginResponse.encryptionType, loginResponse.encryptionSettings);await handleStoreUnlockKeyDerivationParams({ salt: loginResponse.salt, encryptionType: loginResponse.encryptionType, encryptionSettings: loginResponse.encryptionSettings });// Throws an unlock-key-rejected (E-206) error on a wrong password.- unlockKey = credentials.passwordHashBase64;- await VaultKeyService.refreshKeyChain(unlockKey, webApi);+ unlockKey = await VaultKeyService.refreshKeyChain(credentials.passwordHashBase64, webApi);} else {const storedParams = await handleGetUnlockKeyDerivationParams();if (!storedParams) {@@ -159,9 +159,8 @@ export function handleUnlockWithPassword(data: { password: string }): Promise<Bareturn { status: 'error', error: { key: 'common.errors.serverNotAvailable', wrongPassword: false } };}- const credentials = await SrpAuthService.prepareCredentials(data.password, storedParams.salt, storedParams.encryptionSettings);- unlockKey = credentials.passwordHashBase64;- await VaultKeyService.verifyUnlockKey(unlockKey);+ const credentials = await SrpAuthService.prepareCredentials(data.password, storedParams.salt, storedParams.encryptionType, storedParams.encryptionSettings);+ unlockKey = await VaultKeyService.verifyUnlockKey(credentials.passwordHashBase64);}await storeUnlockKey(unlockKey, !status.online, true);@@ -187,8 +186,9 @@ export function handleUnlockWithPassword(data: { password: string }): Promise<Baexport function handleUnlockWithPin(data: { pin: string }): Promise<BackgroundAuthResult> {return runExclusive(async () => {try {- const unlockKey = await unlockWithPin(data.pin);- await VaultKeyService.verifyUnlockKey(unlockKey);+ const pinKey = await unlockWithPin(data.pin);+ const unlockKey = await VaultKeyService.verifyUnlockKey(pinKey);+ await convertLegacyPinKey(data.pin, pinKey, unlockKey);const status = await checkServerStatus(new WebApiService());if ('logout' in status) {@@ -229,19 +229,19 @@ export function handleLoginWithPassword(data: { username: string; password: striconst username = SrpAuthService.normalizeUsername(data.username);const srp = new SrpLoginService(new WebApiService());const loginResponse = await srp.initiateLogin(username);- const { passwordHashString, passwordHashBase64 } = await SrpAuthService.prepareCredentials(data.password, loginResponse.salt, loginResponse.encryptionSettings);- const validation = await srp.validateLogin(username, passwordHashString, data.rememberMe, loginResponse);+ const credentials = await SrpAuthService.prepareLoginCredentials(data.password, loginResponse, username);+ const validation = await srp.validateLogin(username, credentials, data.rememberMe, loginResponse);if (validation.requiresTwoFactor) {// Kept in memory for the 2FA step, which may come from a reopened popup.- handleStoreTwoFactorState({ username, loginResponse, passwordHashString, passwordHashBase64, rememberMe: data.rememberMe });+ handleStoreTwoFactorState({ username, loginResponse, credentials, rememberMe: data.rememberMe });return { status: 'twoFactorRequired', username, rememberMe: data.rememberMe };}if (!validation.token) {return { status: 'error', error: { key: 'common.errors.unknownError', wrongPassword: false } };}- return await completeLogin(username, validation.token.token, validation.token.refreshToken, passwordHashBase64, loginResponse);+ return await completeLogin(username, validation.token.token, validation.token.refreshToken, credentials.passwordHashBase64, loginResponse);} catch (err) {return failureResult('Login error', err);}@@ -260,13 +260,13 @@ export function handleLoginWithTwoFactor(data: { code: string }): Promise<Backgrtry {const srp = new SrpLoginService(new WebApiService());- const validation = await srp.validateLogin2Fa(state.username, state.passwordHashString, state.rememberMe, state.loginResponse, parseInt(data.code));+ const validation = await srp.validateLogin2Fa(state.username, state.credentials, state.rememberMe, state.loginResponse, parseInt(data.code));if (!validation.token) {return { status: 'error', error: { key: 'common.errors.unknownError', wrongPassword: false } };}handleClearTwoFactorState();- return await completeLogin(state.username, validation.token.token, validation.token.refreshToken, state.passwordHashBase64, state.loginResponse);+ return await completeLogin(state.username, validation.token.token, validation.token.refreshToken, state.credentials.passwordHashBase64, state.loginResponse);} catch (err) {return failureResult('2FA error', err);}@@ -283,8 +283,9 @@ async function completeLogin(username: string, token: string, refreshToken: stri// Fetch the key chain and check the unlock key opens it. Not recoverable when it fails, so log out again.const webApi = new WebApiService();+ let storedKey: string;try {- await VaultKeyService.refreshKeyChain(unlockKey, webApi);+ storedKey = await VaultKeyService.refreshKeyChain(unlockKey, webApi);} catch (err) {await webApi.revokeTokens();await handleClearSession();@@ -294,7 +295,7 @@ async function completeLogin(username: string, token: string, refreshToken: striawait handleStoreUnlockKeyDerivationParams({ salt: derivationParams.salt, encryptionType: derivationParams.encryptionType, encryptionSettings: derivationParams.encryptionSettings });// Content scripts are told once the vault is pulled: before that there is nothing to autofill from.- await storeUnlockKey(unlockKey, false, false);+ await storeUnlockKey(storedKey, false, false);const sync = await handleFullVaultSync({ forcePull: true, reportErrorToPopup: false });if (sync.logoutReason === 'clientVersionNotSupported') {diff --git a/apps/browser-extension/src/entrypoints/background/TwoFactorStateHandler.ts b/apps/browser-extension/src/entrypoints/background/TwoFactorStateHandler.tsindex 0ee61f42a..9eff8c70a 100644--- a/apps/browser-extension/src/entrypoints/background/TwoFactorStateHandler.ts+++ b/apps/browser-extension/src/entrypoints/background/TwoFactorStateHandler.ts@@ -8,6 +8,7 @@* so users can close the popup to switch to their authenticator app and continue without re-entering credentials.*/+import type { PreparedCredentials } from '@aliasvault/client/auth/SrpAuthService';import type { LoginResponse } from '@aliasvault/models/webapi';/**@@ -16,8 +17,7 @@ import type { LoginResponse } from '@aliasvault/models/webapi';export type TwoFactorState = {username: string;loginResponse: LoginResponse;- passwordHashString: string;- passwordHashBase64: string;+ credentials: PreparedCredentials;rememberMe: boolean;timestamp: number;};diff --git a/apps/browser-extension/src/entrypoints/background/VaultMessageHandler.ts b/apps/browser-extension/src/entrypoints/background/VaultMessageHandler.tsindex 50184cc61..aab5b4a95 100644--- a/apps/browser-extension/src/entrypoints/background/VaultMessageHandler.ts+++ b/apps/browser-extension/src/entrypoints/background/VaultMessageHandler.ts@@ -195,8 +195,8 @@ export async function handleCheckAuthStatus() : Promise<{ isLoggedIn: boolean, i}/**- * 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.+ * Store the session's key in session storage. It is the one secret the session holds: the vault encryption key and the+ * account private key are derived from it and the cached key chain on demand.*/export async function handleStoreUnlockKey(unlockKey: string,diff --git a/apps/browser-extension/src/entrypoints/popup/context/DbContext.tsx b/apps/browser-extension/src/entrypoints/popup/context/DbContext.tsxindex 4fbd83bb7..fa84d6cfa 100644--- a/apps/browser-extension/src/entrypoints/popup/context/DbContext.tsx+++ b/apps/browser-extension/src/entrypoints/popup/context/DbContext.tsx@@ -372,8 +372,8 @@ export const DbProvider: React.FC<{ children: React.ReactNode }> = ({ children }}, [dbInitialized, loadStoredDatabase]);/**- * 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.+ * Store the session's key in the background worker. It is the one secret the session holds; the vault encryption key+ * is derived from it and the cached key chain.*/const storeUnlockKey = useCallback(async (unlockKey: string) : Promise<void> => {/*diff --git a/apps/browser-extension/src/entrypoints/popup/pages/auth/Login.tsx b/apps/browser-extension/src/entrypoints/popup/pages/auth/Login.tsxindex 2c50748db..42a712ca1 100644--- a/apps/browser-extension/src/entrypoints/popup/pages/auth/Login.tsx+++ b/apps/browser-extension/src/entrypoints/popup/pages/auth/Login.tsx@@ -167,7 +167,7 @@ const Login: React.FC = () => {* @param username - the normalized username* @param token - the access token* @param refreshToken - the refresh token- * @param unlockKey - the unlock key (KEK), base64+ * @param unlockKey - the key the phone sent (its stored key), base64* @param derivationParams - how the unlock key is derived from the password*/const handleSuccessfulAuth = async (@@ -184,8 +184,9 @@ const Login: React.FC = () => {* Fetch the account's key chain, check the unlock key opens it and cache it as-is; the vault encryption key is* derived from the two on demand. Legacy accounts have no chain.*/+ let storedKey: string;try {- await VaultKeyService.refreshKeyChain(unlockKey, webApi);+ storedKey = await VaultKeyService.refreshKeyChain(unlockKey, webApi);} catch (err) {// If key chain can't be fetched, logout user and show error as this is not a recoverable error.await app.logout();@@ -198,8 +199,8 @@ const Login: React.FC = () => {encryptionSettings: derivationParams.encryptionSettings});- // Store the unlock key as the session key, then pull and load the vault.- await dbContext.storeUnlockKey(unlockKey);+ // Store the session key, then pull and load the vault.+ await dbContext.storeUnlockKey(storedKey);await pullAndLoadVault();// Reset prefill flag so next logout will prefill againdiff --git a/apps/browser-extension/src/entrypoints/popup/pages/auth/Unlock.tsx b/apps/browser-extension/src/entrypoints/popup/pages/auth/Unlock.tsxindex 640c9517f..21f8b1e08 100644--- a/apps/browser-extension/src/entrypoints/popup/pages/auth/Unlock.tsx+++ b/apps/browser-extension/src/entrypoints/popup/pages/auth/Unlock.tsx@@ -459,13 +459,11 @@ const Unlock: React.FC = () => {// Set new auth tokensawait authContext.setAuthTokens(result.username, result.token, result.refreshToken);- /*- * The mobile device sends the password-derived key (the KEK).- */- await VaultKeyService.refreshKeyChain(result.unlockKey, webApi);+ // The mobile device sends its stored key.+ const storedKey = await VaultKeyService.refreshKeyChain(result.unlockKey, webApi);- // Store the unlock key and derivation params- await dbContext.storeUnlockKey(result.unlockKey);+ // Store the session key and derivation params+ await dbContext.storeUnlockKey(storedKey);await dbContext.storeUnlockKeyDerivationParams({salt: result.salt,encryptionType: result.encryptionType,diff --git a/apps/browser-extension/src/entrypoints/popup/pages/settings/security/DeleteAccountSettings.tsx b/apps/browser-extension/src/entrypoints/popup/pages/settings/security/DeleteAccountSettings.tsxindex cee6013d1..057a7e737 100644--- a/apps/browser-extension/src/entrypoints/popup/pages/settings/security/DeleteAccountSettings.tsx+++ b/apps/browser-extension/src/entrypoints/popup/pages/settings/security/DeleteAccountSettings.tsx@@ -69,7 +69,7 @@ const DeleteAccountSettings: React.FC = () => {try {showLoading();const initiate = await webApi.post<DeleteAccountInitiateRequest, DeleteAccountInitiateResponse>('Auth/delete-account/initiate', { username: currentUsername });- const prepared = await SrpAuthService.prepareCredentials(password, initiate.salt, initiate.encryptionSettings);+ const prepared = await SrpAuthService.prepareCredentials(password, initiate.salt, initiate.encryptionType, initiate.encryptionSettings);const proof = await SrpAuthService.deriveClientProof(initiate.salt, initiate.srpIdentity, prepared.passwordHashString, initiate.serverEphemeral);await webApi.post<DeleteAccountRequest, unknown>('Auth/delete-account/confirm', { username: currentUsername, clientPublicEphemeral: proof.clientPublicEphemeral, clientSessionProof: proof.clientSessionProof }, false);await auth.clearAuthUserInitiated();diff --git a/apps/browser-extension/src/utils/constants/storageKeys.ts b/apps/browser-extension/src/utils/constants/storageKeys.tsindex a11214ddd..947c20700 100644--- a/apps/browser-extension/src/utils/constants/storageKeys.ts+++ b/apps/browser-extension/src/utils/constants/storageKeys.ts@@ -100,7 +100,7 @@ export const StorageKeys = {/** Whether PIN unlock is enabled. */PIN_ENABLED: 'local:aliasvault_pin_enabled',- /** The unlock key (password-derived KEK), encrypted with the PIN derived key. */+ /** The session's stored key (the Account Key), encrypted with the PIN derived key. */PIN_ENCRYPTED_KEY: 'local:aliasvault_pin_encrypted_key',/** Salt used to derive the PIN key. */PIN_SALT: 'local:aliasvault_pin_salt',diff --git a/apps/browser-extension/tests/helpers/manifest-v2-api.ts b/apps/browser-extension/tests/helpers/manifest-v2-api.tsindex 2979551e2..7f5abfaa6 100644--- a/apps/browser-extension/tests/helpers/manifest-v2-api.ts+++ b/apps/browser-extension/tests/helpers/manifest-v2-api.ts@@ -10,7 +10,7 @@import { createHash } from 'crypto';import { SrpAuthService } from '@aliasvault/client/auth/SrpAuthService';-import { getSyncableTableNames, vaultCodecCanonicalizeFromSqlite, vaultCodecGenerateManifestSalt, vaultCodecPackPayload, vaultCodecUnpackPayload } from '@aliasvault/client/rust/RustCore';+import { deriveKek, getSyncableTableNames, vaultCodecCanonicalizeFromSqlite, vaultCodecGenerateManifestSalt, vaultCodecPackPayload, vaultCodecUnpackPayload } from '@aliasvault/client/rust/RustCore';import { symmetricDecryptBytes, symmetricEncryptBytes } from './vault-crypto';@@ -131,7 +131,8 @@ export async function resolveVaultEncryptionKey(apiBaseUrl: string, token: strinthrow new Error('Vault key chain is missing the encrypted VEK');}- const accountKey = await symmetricDecryptBytes(vaultKey.encryptedAccountKey, derivedKey);+ const kek = Buffer.from(await deriveKek(Buffer.from(derivedKey).toString('base64')), 'base64');+ const accountKey = await symmetricDecryptBytes(vaultKey.encryptedAccountKey, kek);return symmetricDecryptBytes(vaultKey.encryptedVek, accountKey);}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.ktindex b02cd7ca4..69d75e0c9 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@@ -948,7 +948,11 @@ class VaultStore(fun unlockWithPin(pinValue: String): String {val key = pin.unlockWithPin(pinValue)markSuccessfulAuth()- return key++ val accountKey = crypto.openAccountKeyChain(android.util.Base64.decode(key, android.util.Base64.NO_WRAP)).accountKey+ val accountKeyBase64 = android.util.Base64.encodeToString(accountKey, android.util.Base64.NO_WRAP)+ LegacyKeyConversion.convertPinKey(pin, pinValue, key, accountKeyBase64)+ return accountKeyBase64}/**diff --git a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/models/UnlockMethodType.kt b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/models/UnlockMethodType.ktindex 486dbe47f..fc42c1531 100644--- a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/models/UnlockMethodType.kt+++ b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/models/UnlockMethodType.kt@@ -10,7 +10,7 @@ package net.aliasvault.app.vaultstore.models*/object UnlockMethodType {/**- * Master password: the KEK is derived from the password via Argon2.+ * Master password: Argon2id of the password gives the unlock key, which the KEK and SRP input are HKDF-derived from.*/const val PASSWORD = "password"diff --git a/apps/mobile-app/app/login.tsx b/apps/mobile-app/app/login.tsxindex f9bc37025..587fce293 100644--- a/apps/mobile-app/app/login.tsx+++ b/apps/mobile-app/app/login.tsx@@ -1,7 +1,7 @@import { Buffer } from 'buffer';import { describeAuthError, formatErrorMessage } from '@aliasvault/client/auth/AuthErrorMessage';-import { SrpAuthService } from '@aliasvault/client/auth/SrpAuthService';+import { SrpAuthService, type LoginCredentials } from '@aliasvault/client/auth/SrpAuthService';import { SrpLoginService } from '@aliasvault/client/auth/SrpLoginService';import { MaterialIcons } from '@expo/vector-icons';import { LinearGradient } from 'expo-linear-gradient';@@ -63,7 +63,7 @@ export default function LoginScreen() : React.ReactNode {const [twoFactorRequired, setTwoFactorRequired] = useState(false);const [twoFactorCode, setTwoFactorCode] = useState('');const [initiateLoginResponse, setInitiateLoginResponse] = useState<LoginResponse | null>(null);- const [passwordHashString, setPasswordHashString] = useState<string | null>(null);+ const [loginCredentials, setLoginCredentials] = useState<LoginCredentials | null>(null);const [passwordHashBase64, setPasswordHashBase64] = useState<string | null>(null);const [loginStatus, setLoginStatus] = useState<string | null>(null);const [showPassword, setShowPassword] = useState(false);@@ -275,10 +275,9 @@ export default function LoginScreen() : React.ReactNode {await dbContext.storeUnlockKeyDerivationParams(unlockKeyDerivationParams);/*- * 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.+ * The derived key is the unlock key. The Rust core opens the account's key chain with the KEK derived from it+ * (fetched from the server, or the cached one when offline) and caches the chain as-is. The session, biometrics+ * and PIN keep the Account Key and open the chain from it on every unlock.*/await NativeVaultManager.resolveVaultKey(passwordHashBase64);@@ -374,7 +373,7 @@ export default function LoginScreen() : React.ReactNode {authContext.setOfflineMode(false);setTwoFactorRequired(false);setTwoFactorCode('');- setPasswordHashString(null);+ setLoginCredentials(null);setPasswordHashBase64(null);setInitiateLoginResponse(null);setLoginStatus(null);@@ -409,21 +408,21 @@ export default function LoginScreen() : React.ReactNode {initiateLoginResponse.encryptionSettings);- const passwordHashString = Buffer.from(passwordHash).toString('hex').toUpperCase();const passwordHashBase64 = Buffer.from(passwordHash).toString('base64');+ const passwordCredentials = await SrpAuthService.loginCredentials(passwordHashBase64, initiateLoginResponse, credentials.username);setLoginStatus(t('auth.validatingCredentials'));await new Promise(resolve => requestAnimationFrame(resolve));const validationResponse = await srpUtil.validateLogin(SrpAuthService.normalizeUsername(credentials.username),- passwordHashString,+ passwordCredentials,true,initiateLoginResponse);if (validationResponse.requiresTwoFactor) {setInitiateLoginResponse(initiateLoginResponse);- setPasswordHashString(passwordHashString);+ setLoginCredentials(passwordCredentials);setPasswordHashBase64(passwordHashBase64);setTwoFactorRequired(true);setIsLoading(false);@@ -462,7 +461,7 @@ export default function LoginScreen() : React.ReactNode {await new Promise(resolve => requestAnimationFrame(resolve));try {- if (!passwordHashString || !passwordHashBase64 || !initiateLoginResponse) {+ if (!loginCredentials || !passwordHashBase64 || !initiateLoginResponse) {throw new Error('Required login data not found');}@@ -473,7 +472,7 @@ export default function LoginScreen() : React.ReactNode {const validationResponse = await srpUtil.validateLogin2Fa(SrpAuthService.normalizeUsername(credentials.username),- passwordHashString,+ loginCredentials,true,initiateLoginResponse,parseInt(twoFactorCode)@@ -736,7 +735,7 @@ export default function LoginScreen() : React.ReactNode {setCredentials({ username: '', password: '' });setTwoFactorRequired(false);setTwoFactorCode('');- setPasswordHashString(null);+ setLoginCredentials(null);setPasswordHashBase64(null);setInitiateLoginResponse(null);setError(null);diff --git a/apps/mobile-app/hooks/useVaultMutate.ts b/apps/mobile-app/hooks/useVaultMutate.tsindex 9847a49a1..6568d5dd0 100644--- a/apps/mobile-app/hooks/useVaultMutate.ts+++ b/apps/mobile-app/hooks/useVaultMutate.ts@@ -188,8 +188,8 @@ export function useVaultMutate() : {const currentSalt = data.salt;const currentServerEphemeral = data.serverEphemeral;- // Convert base64 string to hex string- const currentPasswordHashString = Buffer.from(currentPasswordHashBase64, 'base64').toString('hex').toUpperCase();+ // The SRP password hash the account's encryption type makes from the unlock key.+ const currentPasswordHashString = await SrpAuthService.srpPasswordHash(currentPasswordHashBase64, data.encryptionType);// Get username from the auth context, always lowercase and trimmed which is required for the argon2id key derivationconst username = authContext.username?.toLowerCase().trim();diff --git a/apps/mobile-app/ios/VaultStoreKit/VaultStore+Crypto.swift b/apps/mobile-app/ios/VaultStoreKit/VaultStore+Crypto.swiftindex 3b90a2062..677197a7c 100644--- a/apps/mobile-app/ios/VaultStoreKit/VaultStore+Crypto.swift+++ b/apps/mobile-app/ios/VaultStoreKit/VaultStore+Crypto.swift@@ -12,7 +12,8 @@ extension VaultStore {salt: String,encryptionType: String,encryptionSettings: String) throws -> Data {- guard encryptionType == "Argon2Id" else {+ // Both types derive the unlock key with Argon2id; they differ only in how the SRP input is made from it.+ guard encryptionType == "Argon2Id" || encryptionType == "Argon2IdHkdf" else {throw NSError(domain: "VaultStore", code: 13, userInfo: [NSLocalizedDescriptionKey: "Unsupported encryption type: \(encryptionType)"])}@@ -23,8 +24,8 @@ extension VaultStore {return derivedKey}- /// 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.+ /// Open a session in memory with the unlock key (the password's Argon2id output) or stored key, without keychain persistence.+ /// Use this to test if a key is valid before persisting.public func storeUnlockKeyInMemory(base64Key: String) throws {guard let keyData = Data(base64Encoded: base64Key) else {throw NSError(domain: "VaultStore", code: 6, userInfo: [NSLocalizedDescriptionKey: "Invalid base64 key"])@@ -42,7 +43,7 @@ extension VaultStore {print("Cleared unlock key from memory")}- /// Open a session in memory with the unlock key (the password-derived KEK) AND persist that key to keychain+ /// Open a session in memory with the unlock key (the password's Argon2id output) or stored key AND persist the stored key to keychain/// if Face ID is enabled.public func storeUnlockKey(base64Key: String) throws {// First open the session in memory@@ -62,20 +63,21 @@ extension VaultStore {}/*- * 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.+ * The stored key is the one secret a session holds; keychain and PIN only protect that same key. It is the+ * Account Key, so it does not depend on the password: a typed password yields an unlock key (its Argon2id+ * output), which opening the chain turns into the Account Key before anything stores it. A key stored before the+ * account had a chain is an unlock key; it still opens the chain and is replaced by the Account Key on the next+ * open. The Account Key opens the vault key and account private key, which are derived on demand and never+ * stored.*/- /// Open a session with the unlock key, after checking that it opens the cached account key chain.+ /// Open a session with a key that opens the cached account key chain; the session keeps the Account Key it yields.internal func openSession(unlockKey: Data) throws {guard unlockKey.count == 32 else {throw NSError(domain: "VaultStore", code: 7, userInfo: [NSLocalizedDescriptionKey: "Invalid key length. Expected 32 bytes"])}- _ = try openAccountKeyChain(with: unlockKey)- self.unlockKey = unlockKey+ self.unlockKey = try openAccountKeyChain(with: unlockKey).accountKey}/// Store the key derivation parameters used for deriving the encryption key from the plain text password@@ -109,36 +111,43 @@ extension VaultStore {return self.userDefaults.string(forKey: VaultConstants.accountKeyChainKey)}- /// 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?) {+ /// The keys an opened account key chain gives.+ internal struct SessionKeys {+ /// The key that encrypts and decrypts the vault.+ let vaultEncryptionKey: Data+ /// The account private key (JWK), nil when the account has no keypair or it does not open.+ let accountPrivateKey: String?+ /// The key to store for later unlocks, in place of the key the chain was opened with.+ let accountKey: Data+ }++ /// Open the cached account key chain with the stored key: the Account Key, or an unlock key that `accountKey` then+ /// replaces (Rust `openAccountKeyChain`). Without a chain (account not yet upgraded) the unlock key is the vault key.+ internal func openAccountKeyChain(with storedKey: Data) throws -> SessionKeys {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, nil)+ return SessionKeys(vaultEncryptionKey: storedKey, accountPrivateKey: nil, accountKey: storedKey)}guard let encryptedVek = chain["encryptedVek"] as? String, !encryptedVek.isEmpty else {throw NSError(domain: "VaultStore", code: 41, userInfo: [NSLocalizedDescriptionKey: "Account key chain is missing the encrypted VEK"])}- guard let accountKey = try? unwrapKey(encryptedAccountKey, with: derivedKey) else {- throw AppError.unlockKeyRejected- }- // The account key opened, so a failure here is a damaged chain and never a wrong password.- let vaultEncryptionKey: Data- do {- vaultEncryptionKey = try unwrapKey(encryptedVek, with: accountKey)- } catch {- throw AppError.keyChainUnreadable(message: error.localizedDescription)- }-// 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)+ let encryptedPrivateKey = (chain["encryptedAccountPrivateKey"] as? String).flatMap { $0.isEmpty ? nil : $0 }+ do {+ let keys = try RustCoreFramework.openAccountKeyChain(+ storedKey: storedKey, encryptedAccountKey: encryptedAccountKey, encryptedVek: encryptedVek, encryptedAccountPrivateKey: encryptedPrivateKey+ )+ return SessionKeys(vaultEncryptionKey: keys.vaultEncryptionKey, accountPrivateKey: keys.accountPrivateKey, accountKey: keys.accountKey)+ } catch KeyChainError.UnlockKeyRejected {+ throw AppError.unlockKeyRejected+ } catch KeyChainError.KeyChainUnreadable(let message) {+ // The account key opened, so this is a damaged chain and never a wrong password.+ throw AppError.keyChainUnreadable(message: message)}- return (vaultEncryptionKey, accountPrivateKey)}/// Decrypt base64 RSA-OAEP ciphertext with the session's account private key as UTF-8 text, or nil when the session holds@@ -150,17 +159,8 @@ extension VaultStore {return String(data: plaintext, encoding: .utf8)}- /// Decrypt a wrapped key with the given key.- private func unwrapKey(_ base64Blob: String, with key: Data) throws -> Data {- guard let blob = Data(base64Encoded: base64Blob) else {- throw NSError(domain: "VaultStore", code: 42, userInfo: [NSLocalizedDescriptionKey: "Invalid wrapped key"])- }-- let sealedBox = try AES.GCM.SealedBox(combined: blob)- return try AES.GCM.open(sealedBox, using: SymmetricKey(data: key))- }-- /// Verify the password and return the unlock key (the password-derived KEK, base64) if correct.+ /// Verify the password and return its unlock key (base64) if correct. Callers derive the SRP input from it for the+ /// account's encryption type; `storeUnlockKey` turns it into the Account Key the session keeps.public func verifyPassword(_ password: String) -> String? {do {// Get encryption key derivation parameters@@ -173,7 +173,7 @@ extension VaultStore {return nil}- // Derive the KEK from the password and unwrap the chain; a wrong password fails the unwrap.+ // Derive the unlock key 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 vaultEncryptionKey = try openAccountKeyChain(with: derivedKey).vaultEncryptionKey@@ -196,15 +196,6 @@ extension VaultStore {}}- /// Answer a server's SRP challenge with the unlock key of the open session.- public func deriveSrpProof(salt: String, srpIdentity: String, serverEphemeral: String) throws -> (clientPublicEphemeral: String, clientSessionProof: String) {- let passwordHash = try getUnlockKey().map { String(format: "%02X", $0) }.joined()- let ephemeral = RustCoreFramework.srpGenerateEphemeral()- let privateKey = try RustCoreFramework.srpDerivePrivateKey(salt: salt, identity: srpIdentity, passwordHash: passwordHash)- let session = try RustCoreFramework.srpDeriveSession(clientSecret: ephemeral.secret, serverPublic: serverEphemeral, salt: salt, identity: srpIdentity, privateKey: privateKey)- return (ephemeral.public, session.proof)- }-/// Encrypt the data using the encryption keyinternal func encrypt(data: Data) throws -> Data {let encryptionKey = try getEncryptionKey()@@ -281,7 +272,15 @@ extension VaultStore {/// Get the encryption key - the key used to encrypt and decrypt the vault.internal func getEncryptionKey() throws -> Data {- return try openAccountKeyChain(with: try getUnlockKey()).vaultEncryptionKey+ let storedKey = try getUnlockKey()+ let keys = try openAccountKeyChain(with: storedKey)+ if keys.accountKey != storedKey {+ // The session held an unlock key and the account has a key chain since (a sync accepted one created on+ // another device): keep the Account Key from now on.+ self.unlockKey = keys.accountKey+ convertLegacyKeychainKey(keychainKey: storedKey, accountKey: keys.accountKey)+ }+ return keys.vaultEncryptionKey}/// Get the session's stored key, which the keychain and PIN protect.diff --git a/apps/server/Databases/AliasServerDb/UserSrpCredentials.cs b/apps/server/Databases/AliasServerDb/UserSrpCredentials.csindex 9a1e4e395..e68dfe732 100644--- a/apps/server/Databases/AliasServerDb/UserSrpCredentials.cs+++ b/apps/server/Databases/AliasServerDb/UserSrpCredentials.cs@@ -12,7 +12,7 @@ namespace AliasServerDb;/// </summary>/// <param name="Salt">The SRP salt.</param>/// <param name="Verifier">The SRP verifier the server checks a client's proof against.</param>-/// <param name="EncryptionType">The KDF the client derives its KEK with, e.g. Argon2Id.</param>+/// <param name="EncryptionType">How the client derives the SRP input from the password: Argon2IdHkdf, or legacy Argon2Id.</param>/// <param name="EncryptionSettings">The parameters belonging to the KDF named by <paramref name="EncryptionType"/>.</param>/// <param name="UnlockKeyId">The <see cref="UserUnlockKey"/> these credentials came from, or null for a legacy user whose credentials still live on the vault manifest.</param>public sealed record UserSrpCredentials(string Salt, string Verifier, string EncryptionType, string EncryptionSettings, Guid? UnlockKeyId = null);diff --git a/apps/server/Databases/AliasServerDb/VaultKeyMetadata.cs b/apps/server/Databases/AliasServerDb/VaultKeyMetadata.csindex 7febb8210..ceb941389 100644--- a/apps/server/Databases/AliasServerDb/VaultKeyMetadata.cs+++ b/apps/server/Databases/AliasServerDb/VaultKeyMetadata.cs@@ -35,7 +35,7 @@ public sealed class VaultKeyMetadatapublic string? SrpVerifier { get; set; }/// <summary>- /// Gets or sets the KDF the client derives the KEK with, e.g. <c>Argon2Id</c>.+ /// Gets or sets how the client derives the SRP input from the password: <c>Argon2IdHkdf</c>, or legacy <c>Argon2Id</c>./// </summary>public string? EncryptionType { get; set; }diff --git a/apps/server/Shared/AliasVault.Shared/Models/Enums/UnlockMethodType.cs b/apps/server/Shared/AliasVault.Shared/Models/Enums/UnlockMethodType.csindex de57416e8..18294b229 100644--- a/apps/server/Shared/AliasVault.Shared/Models/Enums/UnlockMethodType.cs+++ b/apps/server/Shared/AliasVault.Shared/Models/Enums/UnlockMethodType.cs@@ -14,7 +14,7 @@ namespace AliasVault.Shared.Models.Enums;public enum UnlockMethodType{/// <summary>- /// Master password: the KEK is derived from the password via Argon2.+ /// Master password: Argon2id of the password gives the unlock key, which the KEK and SRP input are HKDF-derived from./// </summary>Password = 0,}diff --git a/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Auth/RegisterRequest.cs b/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Auth/RegisterRequest.csindex d288a7234..00d85f58c 100644--- a/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Auth/RegisterRequest.cs+++ b/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Auth/RegisterRequest.cs@@ -77,7 +77,7 @@ public class RegisterRequestpublic string? EncryptedVek { get; }/// <summary>- /// Gets the Account Key encrypted with the password-derived KEK.+ /// Gets the Account Key encrypted with the KEK derived from the password./// </summary>public string? EncryptedAccountKey { get; }diff --git a/apps/web/src/pages/auth/Login.tsx b/apps/web/src/pages/auth/Login.tsxindex 9569f963a..99d64e47a 100644--- a/apps/web/src/pages/auth/Login.tsx+++ b/apps/web/src/pages/auth/Login.tsx@@ -1,6 +1,6 @@import { extractErrorCode } from '@aliasvault/client/api/errors/AppErrorCodes';import { describeAuthError, formatErrorMessage } from '@aliasvault/client/auth/AuthErrorMessage';-import { SrpAuthService } from '@aliasvault/client/auth/SrpAuthService';+import { SrpAuthService, type PreparedCredentials } from '@aliasvault/client/auth/SrpAuthService';import { SrpLoginService } from '@aliasvault/client/auth/SrpLoginService';import { VaultKeyService } from '@aliasvault/client/auth/VaultKeyService';import { getPlatform } from '@aliasvault/client/platform';@@ -57,8 +57,7 @@ const Login: React.FC = () => {const [recoveryCode, setRecoveryCode] = useState('');const [errors, setErrors] = useState<string[]>([]);const [loginResponse, setLoginResponse] = useState<LoginResponse | null>(null);- const [passwordHashString, setPasswordHashString] = useState<string | null>(null);- const [passwordHashBase64, setPasswordHashBase64] = useState<string | null>(null);+ const [credentials, setCredentials] = useState<PreparedCredentials | null>(null);const [showMobileLoginModal, setShowMobileLoginModal] = useState(false);const usernameRef = useRef<HTMLInputElement>(null);const twoFactorRef = useRef<HTMLInputElement>(null);@@ -119,15 +118,16 @@ const Login: React.FC = () => {await auth.setAuthTokens(SrpAuthService.normalizeUsername(loginUsername), accessToken, refreshToken);// Fetch the key chain, check the unlock key opens it and cache it; the vault key is derived from the two on demand.+ let storedKey: string;try {- await VaultKeyService.refreshKeyChain(unlockKey, webApi);+ storedKey = await VaultKeyService.refreshKeyChain(unlockKey, webApi);} catch (err) {// Without a usable key chain the session is useless; end it so the error shows on this form.await auth.logout();throw err;}await vaultStore.storeUnlockKeyDerivationParams(params);- await vaultStore.storeUnlockKey(unlockKey);+ await vaultStore.storeUnlockKey(storedKey);notifications.clearMessages();navigate('/sync', { replace: true });@@ -178,14 +178,13 @@ const Login: React.FC = () => {const normalizedUsername = SrpAuthService.normalizeUsername(username);const response = await srpUtil.initiateLogin(normalizedUsername);- // Derive the KEK from the password.- const prepared = await SrpAuthService.prepareCredentials(password, response.salt, response.encryptionSettings);- const validateLoginResponse = await srpUtil.validateLogin(normalizedUsername, prepared.passwordHashString, rememberMe, response);+ // Derive the unlock key and the SRP password hash from the password.+ const prepared = await SrpAuthService.prepareLoginCredentials(password, response, normalizedUsername);+ const validateLoginResponse = await srpUtil.validateLogin(normalizedUsername, prepared, rememberMe, response);if (validateLoginResponse.requiresTwoFactor) {setLoginResponse(response);- setPasswordHashString(prepared.passwordHashString);- setPasswordHashBase64(prepared.passwordHashBase64);+ setCredentials(prepared);setStep('two-factor');return;}@@ -207,15 +206,15 @@ const Login: React.FC = () => {setErrors([]);try {- if (!loginResponse || !passwordHashString || !passwordHashBase64) {+ if (!loginResponse || !credentials) {throw new Error(t('auth.loginForm.loginRequestErrorMessage'));}const code = twoFactorCode.trim();if (!/^\d{6}$/.test(code)) {throw new Error(t('common.errors.invalidCode'));}- const validateLoginResponse = await srpUtil.validateLogin2Fa(username, passwordHashString, rememberMe || rememberMachine, loginResponse, parseInt(code, 10));- await processLoginVerify(validateLoginResponse, passwordHashBase64, loginResponse);+ const validateLoginResponse = await srpUtil.validateLogin2Fa(username, credentials, rememberMe || rememberMachine, loginResponse, parseInt(code, 10));+ await processLoginVerify(validateLoginResponse, credentials.passwordHashBase64, loginResponse);} catch (err) {setErrors(await toErrorMessages(err));} finally {@@ -232,11 +231,11 @@ const Login: React.FC = () => {setErrors([]);try {- if (!loginResponse || !passwordHashString || !passwordHashBase64) {+ if (!loginResponse || !credentials) {throw new Error(t('auth.loginForm.loginRequestErrorMessage'));}- const validateLoginResponse = await srpUtil.validateLoginRecoveryCode(username, passwordHashString, rememberMe, loginResponse, recoveryCode.trim());- await processLoginVerify(validateLoginResponse, passwordHashBase64, loginResponse);+ const validateLoginResponse = await srpUtil.validateLoginRecoveryCode(username, credentials, rememberMe, loginResponse, recoveryCode.trim());+ await processLoginVerify(validateLoginResponse, credentials.passwordHashBase64, loginResponse);} catch (err) {setErrors(await toErrorMessages(err));} finally {diff --git a/apps/web/src/pages/auth/Unlock.tsx b/apps/web/src/pages/auth/Unlock.tsxindex 95f4c3594..6ff6a570a 100644--- a/apps/web/src/pages/auth/Unlock.tsx+++ b/apps/web/src/pages/auth/Unlock.tsx@@ -167,17 +167,15 @@ const Unlock: React.FC = () => {if (!params) {throw new Error(t('auth.unlockPage.connectionFailedError'));}- const prepared = await SrpAuthService.prepareCredentials(password, params.salt, params.encryptionSettings);- unlockKey = prepared.passwordHashBase64;+ const prepared = await SrpAuthService.prepareCredentials(password, params.salt, params.encryptionType, params.encryptionSettings);// Throws an unlock-key-rejected (E-206) error on a wrong password.- await VaultKeyService.verifyUnlockKey(unlockKey);+ unlockKey = await VaultKeyService.verifyUnlockKey(prepared.passwordHashBase64);} else {const loginResponse = await srpUtil.initiateLogin(username);- const prepared = await SrpAuthService.prepareCredentials(password, loginResponse.salt, loginResponse.encryptionSettings);+ const prepared = await SrpAuthService.prepareCredentials(password, loginResponse.salt, loginResponse.encryptionType, loginResponse.encryptionSettings);await vaultStore.storeUnlockKeyDerivationParams({ salt: loginResponse.salt, encryptionType: loginResponse.encryptionType, encryptionSettings: loginResponse.encryptionSettings });- unlockKey = prepared.passwordHashBase64;// Throws an unlock-key-rejected (E-206) error on a wrong password.- await VaultKeyService.refreshKeyChain(unlockKey, webApi);+ unlockKey = await VaultKeyService.refreshKeyChain(prepared.passwordHashBase64, webApi);}await vaultStore.storeUnlockKey(unlockKey);@@ -219,9 +217,9 @@ const Unlock: React.FC = () => {await auth.setAuthTokens(result.username, result.token, result.refreshToken);// Throws an unlock-key-rejected (E-206) error if the key does not open the key chain.- await VaultKeyService.refreshKeyChain(result.unlockKey, webApi);+ const storedKey = await VaultKeyService.refreshKeyChain(result.unlockKey, webApi);await vaultStore.storeUnlockKeyDerivationParams({ salt: result.salt, encryptionType: result.encryptionType, encryptionSettings: result.encryptionSettings });- await vaultStore.storeUnlockKey(result.unlockKey);+ await vaultStore.storeUnlockKey(storedKey);navigate('/sync', { replace: true });} catch (err) {console.error('Mobile unlock error:', err);diff --git a/apps/web/src/pages/settings/security/DeleteAccount.tsx b/apps/web/src/pages/settings/security/DeleteAccount.tsxindex 8583a5571..b3487cfa4 100644--- a/apps/web/src/pages/settings/security/DeleteAccount.tsx+++ b/apps/web/src/pages/settings/security/DeleteAccount.tsx@@ -67,7 +67,7 @@ const DeleteAccount: React.FC = () => {notifications.clearMessages();try {const initiate = await webApi.post<DeleteAccountInitiateRequest, DeleteAccountInitiateResponse>('Auth/delete-account/initiate', { username: currentUsername });- const prepared = await SrpAuthService.prepareCredentials(password, initiate.salt, initiate.encryptionSettings);+ const prepared = await SrpAuthService.prepareCredentials(password, initiate.salt, initiate.encryptionType, initiate.encryptionSettings);const proof = await SrpAuthService.deriveClientProof(initiate.salt, initiate.srpIdentity, prepared.passwordHashString, initiate.serverEphemeral);await webApi.post<DeleteAccountRequest, unknown>('Auth/delete-account/confirm', { username: currentUsername, clientPublicEphemeral: proof.clientPublicEphemeral, clientSessionProof: proof.clientSessionProof }, false);navigate('/user/logout');diff --git a/apps/web/src/utils/LegacyStorageCleanup.ts b/apps/web/src/utils/LegacyStorageCleanup.tsindex c533e0a0b..762e495b7 100644--- a/apps/web/src/utils/LegacyStorageCleanup.ts+++ b/apps/web/src/utils/LegacyStorageCleanup.ts@@ -3,8 +3,9 @@ import { getLocalPreference, removeLocalPreference, setLocalPreference } from '@import { LocalPreferenceKeys } from '@/utils/StorageKeys';/**- * localStorage keys only the previous (Blazor) web client wrote: its tokens, its cached key chain, debug keys and- * its own language key. This app keeps its session in IndexedDB, so none of them is read any more.+ * localStorage keys only the previous (Blazor) web client wrote: its tokens, its cached key chain, debug keys, its+ * passkey unlock (which held the password-derived key; passkey unlock is set up again in this app) and its own+ * language key. This app keeps its session in IndexedDB, so none of them is read any more.*/const LEGACY_ONLY_KEYS = ['token',@@ -16,6 +17,10 @@ const LEGACY_ONLY_KEYS = ['encryptionKeyDerivationParams','debugSessionKeys','encryptionTestString',+ 'webAuthnEnabled',+ 'webAuthnCredentialId',+ 'webAuthnSalt',+ 'webAuthnEncryptedEncryptionKey','webAuthnCredentialDerivedKey','blazorCulture',];diff --git a/apps/web/src/utils/WebAuthnService.ts b/apps/web/src/utils/WebAuthnService.tsindex b9af7c432..b41cbd4df 100644--- a/apps/web/src/utils/WebAuthnService.ts+++ b/apps/web/src/utils/WebAuthnService.ts@@ -7,21 +7,14 @@ import { base64ToBytes, bytesToBase64 } from '@aliasvault/client/utilities/Base6import { getLocalPreference, removeLocalPreference, setLocalPreference } from '@/utils/LocalPreferences';import { StorageKeys } from '@/utils/StorageKeys';-/** Local storage keys for the WebAuthn quick unlock. */+/** Local storage keys for the WebAuthn quick unlock; the previous web client's keys are removed by LegacyStorageCleanup. */const KEYS = {- enabled: 'webAuthnEnabled',- credentialId: 'webAuthnCredentialId',- salt: 'webAuthnSalt',- encryptedKeys: 'webAuthnEncryptedEncryptionKey',+ enabled: 'webAuthnUnlockEnabled',+ credentialId: 'webAuthnUnlockCredentialId',+ salt: 'webAuthnUnlockSalt',+ encryptedAccountKey: 'webAuthnEncryptedAccountKey',} as const;-/**- * What the passkey-derived key encrypts: the session unlock key (the KEK), never the keys the chain opens.- */-type WebAuthnSessionKeys = {- UnlockKey: string;-};-/*** Thrown when the browser or authenticator has no PRF support.*/@@ -122,7 +115,7 @@ async function createCredentialDerivedKey(username: string): Promise<{ credentia}/**- * Passkey quick unlock: the session unlock key encrypted with a key the passkey derives, kept in localStorage.+ * Passkey quick unlock: the session's Account Key encrypted with a key the passkey derives, kept in localStorage.*/export const WebAuthnService = {/**@@ -133,70 +126,51 @@ export const WebAuthnService = {},/**- * Create a passkey and encrypt the current session unlock key with it.+ * Create a passkey and encrypt the session's Account Key with it.*/async enable(username: string): Promise<void> {- const unlockKey = await VaultKeyService.getSessionUnlockKey();- if (!unlockKey) {+ const accountKey = await VaultKeyService.getSessionUnlockKey();+ if (!accountKey) {throw new Error('Vault is locked');}const credential = await createCredentialDerivedKey(username);- const payload: WebAuthnSessionKeys = { UnlockKey: unlockKey };- const encrypted = await EncryptionUtility.symmetricEncrypt(JSON.stringify(payload), credential.derivedKey);setLocalPreference(KEYS.credentialId, credential.credentialId);setLocalPreference(KEYS.salt, credential.salt);- setLocalPreference(KEYS.encryptedKeys, encrypted);+ setLocalPreference(KEYS.encryptedAccountKey, await EncryptionUtility.symmetricEncrypt(accountKey, credential.derivedKey));setLocalPreference(KEYS.enabled, 'true');},/**- * Forget the passkey and the encrypted unlock key.+ * Forget the passkey and the encrypted Account Key.*/disable(): void {setLocalPreference(KEYS.enabled, 'false');removeLocalPreference(KEYS.credentialId);removeLocalPreference(KEYS.salt);- removeLocalPreference(KEYS.encryptedKeys);+ removeLocalPreference(KEYS.encryptedAccountKey);},/**- * Decrypt the unlock key with the passkey, check it opens the key chain and put it in the session.+ * Decrypt the Account Key with the passkey, check it opens the key chain and put it in the session.*/async unlock(): Promise<void> {const credentialId = getLocalPreference(KEYS.credentialId);const salt = getLocalPreference(KEYS.salt);- const encrypted = getLocalPreference(KEYS.encryptedKeys);+ const encrypted = getLocalPreference(KEYS.encryptedAccountKey);if (!credentialId || !salt || !encrypted) {throw new Error('WebAuthn encrypted encryption key is not set or WebAuthn credential ID is not set.');}const derivedKey = await getCredentialDerivedKey(credentialId, salt);- const payload = await EncryptionUtility.symmetricDecrypt(encrypted, derivedKey);- let keys: WebAuthnSessionKeys | null = null;+ const accountKey = await EncryptionUtility.symmetricDecrypt(encrypted, derivedKey);try {- keys = JSON.parse(payload) as WebAuthnSessionKeys;- } catch {- keys = null;- }-- /*- * Check for legacy storage (pre-0.31.0).- * TODO: this can be removed in a future release once 0.31.0 has been released.- */- const isLegacyStore = typeof keys?.UnlockKey !== 'string';- const unlockKey = keys && !isLegacyStore ? keys.UnlockKey : payload;- try {- await VaultKeyService.verifyUnlockKey(unlockKey);+ await VaultKeyService.verifyUnlockKey(accountKey);} catch (error) {- // A key the chain rejects (password changed since) is discarded, the password unlock still works.+ // A key the chain rejects is discarded, the password unlock still works.if (error instanceof Error && extractErrorCode(error.message) === AppErrorCode.UNLOCK_KEY_REJECTED) {WebAuthnService.disable();}throw error;}- if (isLegacyStore) {- const upgraded: WebAuthnSessionKeys = { UnlockKey: unlockKey };- setLocalPreference(KEYS.encryptedKeys, await EncryptionUtility.symmetricEncrypt(JSON.stringify(upgraded), derivedKey));- }- await getPlatform().storage.set(StorageKeys.UNLOCK_KEY, unlockKey);+ await getPlatform().storage.set(StorageKeys.UNLOCK_KEY, accountKey);},};diff --git a/core/client/src/auth/MasterPasswordService.ts b/core/client/src/auth/MasterPasswordService.tsindex a16e55cc6..89ad79d8d 100644--- a/core/client/src/auth/MasterPasswordService.ts+++ b/core/client/src/auth/MasterPasswordService.ts@@ -1,5 +1,5 @@import { StorageKeys } from '../constants/StorageKeys';-import { EncryptionUtility } from '../crypto/EncryptionUtility';+import { unwrapAccountKey, wrapAccountKey } from '../crypto/AccountKeys';import { getPlatform } from '../platform/ClientPlatform';import { VaultSyncHoldReason, withVaultSyncHold } from '../sync/VaultSyncHold';@@ -38,6 +38,7 @@ export class PasswordChangedElsewhereError extends Error {export type SrpChallenge = {salt: string;serverEphemeral: string;+ encryptionType: string;encryptionSettings: string;srpIdentity?: string;};@@ -45,7 +46,7 @@ export type SrpChallenge = {/** The answer to an SRP challenge, plus what the same derivation yields for local key material. */export type SrpChallengeAnswer = {proof: SrpClientProof;- kekBase64: string;+ unlockKeyBase64: string;srpIdentity: string;};@@ -75,12 +76,12 @@ export class MasterPasswordService {/*** Answer a server's SRP challenge with the master password. The password goes no further than the derivation;- * the KEK it yields comes along for callers that also need to open local key material.+ * the unlock key it yields comes along for callers that also need to open local key material.* @param challenge - the challenge the endpoint's initiate call returned* @param password - the master password to prove*/public static async answerSrpChallenge(challenge: SrpChallenge, password: string): Promise<SrpChallengeAnswer> {- const credentials = await SrpAuthService.prepareCredentials(password, challenge.salt, challenge.encryptionSettings);+ const credentials = await SrpAuthService.prepareCredentials(password, challenge.salt, challenge.encryptionType, challenge.encryptionSettings);/** Use srpIdentity from the challenge if available, otherwise fall back to the normalized username.@@ -90,24 +91,24 @@ export class MasterPasswordService {const srpIdentity = challenge.srpIdentity ?? SrpAuthService.normalizeUsername(username ?? '');const proof = await SrpAuthService.deriveClientProof(challenge.salt, srpIdentity, credentials.passwordHashString, challenge.serverEphemeral);- return { proof, kekBase64: credentials.passwordHashBase64, srpIdentity };+ return { proof, unlockKeyBase64: credentials.passwordHashBase64, srpIdentity };}/**- * Re-encrypt the Account Key for a new password: open it with the old KEK, encrypt it with the new one.- * @param encryptedAccountKey - the Account Key encrypted with the old password-derived KEK- * @param oldKekBase64 - the KEK derived from the current password- * @param newKekBase64 - the KEK derived from the new password+ * Re-encrypt the Account Key for a new password: open it with the old password's KEK, encrypt it with the new one's.+ * @param encryptedAccountKey - the Account Key encrypted with the KEK of the current password+ * @param oldUnlockKeyBase64 - the unlock key of the current password+ * @param newUnlockKeyBase64 - the unlock key of the new password* @returns The decrypted Account Key and its new wrapping.- * @throws {IncorrectPasswordError} when the old KEK does not open the blob (wrong current password).+ * @throws {IncorrectPasswordError} when the old unlock key does not open the blob (wrong current password).*/- public static async reencryptAccountKey(encryptedAccountKey: string, oldKekBase64: string, newKekBase64: string): Promise<{ accountKey: string; newEncryptedAccountKey: string }> {- const accountKey = await MasterPasswordService.decryptAccountKey(encryptedAccountKey, oldKekBase64);- return { accountKey, newEncryptedAccountKey: await EncryptionUtility.encryptVaultEncryptionKey(accountKey, newKekBase64) };+ public static async reencryptAccountKey(encryptedAccountKey: string, oldUnlockKeyBase64: string, newUnlockKeyBase64: string): Promise<{ accountKey: string; newEncryptedAccountKey: string }> {+ const accountKey = await MasterPasswordService.decryptAccountKey(encryptedAccountKey, oldUnlockKeyBase64);+ return { accountKey, newEncryptedAccountKey: await wrapAccountKey(accountKey, newUnlockKeyBase64) };}/**- * Change the master password by re-encrypting the Account Key using a new KEK.+ * Change the master password by re-encrypting the Account Key using the new password's KEK.* @param webApi - the API client to use* @param currentPassword - the current master password* @param newPassword - the new master password@@ -139,8 +140,8 @@ export class MasterPasswordService {const current = await MasterPasswordService.answerSrpChallenge(challenge, currentPassword);const next = await SrpAuthService.prepareNewPassword(newPassword, current.srpIdentity);- // Re-encrypt the Account Key using the new KEK.- const { newEncryptedAccountKey } = await MasterPasswordService.reencryptAccountKey(encryptedAccountKey, current.kekBase64, next.kekBase64);+ // Re-encrypt the Account Key using the new password's KEK.+ const { accountKey, newEncryptedAccountKey } = await MasterPasswordService.reencryptAccountKey(encryptedAccountKey, current.unlockKeyBase64, next.unlockKeyBase64);await webApi.post<PasswordChangeRequest, void>('Auth/change-password', {currentClientPublicEphemeral: current.proof.clientPublicEphemeral,@@ -153,17 +154,17 @@ 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 }, next.kekBase64);+ await VaultKeyService.persistNewAccountKey(newEncryptedAccountKey, { salt: next.salt, encryptionType: next.encryptionType, encryptionSettings: next.encryptionSettings }, accountKey);}/*** Decrypt the KEK-wrapped Account Key.- * @param encryptedAccountKey - the Account Key encrypted with the password-derived KEK- * @param kekBase64 - the KEK derived from the entered password+ * @param encryptedAccountKey - the Account Key encrypted with the KEK of the entered password+ * @param unlockKeyBase64 - the unlock key derived from the entered password*/- private static async decryptAccountKey(encryptedAccountKey: string, kekBase64: string): Promise<string> {+ private static async decryptAccountKey(encryptedAccountKey: string, unlockKeyBase64: string): Promise<string> {try {- return await EncryptionUtility.decryptVaultEncryptionKey(encryptedAccountKey, kekBase64);+ return await unwrapAccountKey(encryptedAccountKey, unlockKeyBase64);} catch {throw new IncorrectPasswordError();}diff --git a/core/client/src/auth/MobileLoginService.ts b/core/client/src/auth/MobileLoginService.tsindex ae516a4e9..a7e217a0d 100644--- a/core/client/src/auth/MobileLoginService.ts+++ b/core/client/src/auth/MobileLoginService.ts@@ -153,7 +153,7 @@ export class MobileLoginService {const privateKey = this.privateKey!;this.cleanup();- // The mobile app encrypted the unlock key with our public key.+ // The mobile app encrypted its stored key with our public key.const unlockKey = bytesToBase64(await EncryptionUtility.decryptWithPrivateKeyObject(data.encryptedUnlockKey, privateKey));// The server encrypted the session payload with a symmetric key, which is encrypted with our public key.diff --git a/core/client/src/auth/SrpLoginService.ts b/core/client/src/auth/SrpLoginService.tsindex 117d0f923..209447810 100644--- a/core/client/src/auth/SrpLoginService.ts+++ b/core/client/src/auth/SrpLoginService.ts@@ -1,7 +1,7 @@import { ApiRequestError } from '../api/errors/ApiRequestError';import { throwIfServerPredatesV2Api } from '../sync/LegacyStorageModelMigration';-import { SrpAuthService, type SrpClientSession } from './SrpAuthService';+import { SrpAuthService, type LoginCredentials, type SrpClientSession } from './SrpAuthService';import type { WebApiService } from '../api/WebApiService';import type { AccountKeyHierarchy } from '../crypto/AccountKeys';@@ -70,47 +70,47 @@ export class SrpLoginService {/*** Validate login with the server using the locally generated ephemeral and session proof.* @param username - The username- * @param passwordHashString - The password hash as uppercase hex+ * @param credentials - The SRP password hash and, for a legacy verifier, its upgrade* @param rememberMe - Whether to request an extended token lifetime* @param loginResponse - The initiate response* @returns The validate response*/- public async validateLogin(username: string, passwordHashString: string, rememberMe: boolean, loginResponse: LoginResponse): Promise<ValidateLoginResponse> {+ public async validateLogin(username: string, credentials: LoginCredentials, rememberMe: boolean, loginResponse: LoginResponse): Promise<ValidateLoginResponse> {const normalizedUsername = SrpAuthService.normalizeUsername(username);- const session = await SrpAuthService.deriveLoginSession(loginResponse, normalizedUsername, passwordHashString);- const model: ValidateLoginRequest = { username: normalizedUsername, rememberMe, ...session.proof };+ const session = await SrpAuthService.deriveLoginSession(loginResponse, normalizedUsername, credentials.passwordHashString);+ const model: ValidateLoginRequest = { username: normalizedUsername, rememberMe, ...session.proof, ...credentials.srpUpgrade };return this.verifiedLoginResponse(session, await this.post('Auth/validate', model));}/*** Validate login with a 2FA authenticator code.* @param username - The username- * @param passwordHashString - The password hash as uppercase hex+ * @param credentials - The SRP password hash and, for a legacy verifier, its upgrade* @param rememberMe - Whether to request an extended token lifetime* @param loginResponse - The initiate response* @param code2Fa - The authenticator code* @returns The validate response*/- public async validateLogin2Fa(username: string, passwordHashString: string, rememberMe: boolean, loginResponse: LoginResponse, code2Fa: number): Promise<ValidateLoginResponse> {+ public async validateLogin2Fa(username: string, credentials: LoginCredentials, rememberMe: boolean, loginResponse: LoginResponse, code2Fa: number): Promise<ValidateLoginResponse> {const normalizedUsername = SrpAuthService.normalizeUsername(username);- const session = await SrpAuthService.deriveLoginSession(loginResponse, normalizedUsername, passwordHashString);- const model: ValidateLoginRequest2Fa = { username: normalizedUsername, rememberMe, ...session.proof, code2Fa };+ const session = await SrpAuthService.deriveLoginSession(loginResponse, normalizedUsername, credentials.passwordHashString);+ const model: ValidateLoginRequest2Fa = { username: normalizedUsername, rememberMe, ...session.proof, ...credentials.srpUpgrade, code2Fa };return this.verifiedLoginResponse(session, await this.post('Auth/validate-2fa', model));}/*** Validate login with a 2FA recovery code.* @param username - The username- * @param passwordHashString - The password hash as uppercase hex+ * @param credentials - The SRP password hash and, for a legacy verifier, its upgrade* @param rememberMe - Whether to request an extended token lifetime* @param loginResponse - The initiate response* @param recoveryCode - The recovery code* @returns The validate response*/- public async validateLoginRecoveryCode(username: string, passwordHashString: string, rememberMe: boolean, loginResponse: LoginResponse, recoveryCode: string): Promise<ValidateLoginResponse> {+ public async validateLoginRecoveryCode(username: string, credentials: LoginCredentials, rememberMe: boolean, loginResponse: LoginResponse, recoveryCode: string): Promise<ValidateLoginResponse> {const normalizedUsername = SrpAuthService.normalizeUsername(username);- const session = await SrpAuthService.deriveLoginSession(loginResponse, normalizedUsername, passwordHashString);- const model: ValidateLoginRequestRecoveryCode = { username: normalizedUsername, rememberMe, ...session.proof, recoveryCode };+ const session = await SrpAuthService.deriveLoginSession(loginResponse, normalizedUsername, credentials.passwordHashString);+ const model: ValidateLoginRequestRecoveryCode = { username: normalizedUsername, rememberMe, ...session.proof, ...credentials.srpUpgrade, recoveryCode };return this.verifiedLoginResponse(session, await this.post('Auth/validate-recovery-code', model));}diff --git a/core/client/src/constants/StorageKeys.ts b/core/client/src/constants/StorageKeys.tsindex e0b56a7b2..2a8d93d55 100644--- a/core/client/src/constants/StorageKeys.ts+++ b/core/client/src/constants/StorageKeys.ts@@ -45,7 +45,7 @@ export const StorageKeys = {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. */+ /** The Account Key encrypted with the KEK derived from the password, as returned by the server. */ENCRYPTED_ACCOUNT_KEY: 'local:encryptedAccountKey',/** The account public key, used for encrypting shared-manifest VEK grants. */ACCOUNT_PUBLIC_KEY: 'local:accountPublicKey',diff --git a/core/client/src/crypto/AccountKeys.ts b/core/client/src/crypto/AccountKeys.tsindex 62791474b..8dbe1b999 100644--- a/core/client/src/crypto/AccountKeys.ts+++ b/core/client/src/crypto/AccountKeys.ts@@ -1,3 +1,5 @@+import { deriveKek } from '../rust/RustCore';+import { EncryptionUtility } from './EncryptionUtility';/**@@ -20,11 +22,29 @@ export type AccountKeyHierarchy = {accountKeys: AccountKeyBlobs;};+/**+ * Wrap the Account Key with the KEK derived from an unlock key.+ * @param accountKey - the Account Key (base64)+ * @param unlockKey - the unlock key (base64), the Argon2id output of the master password+ */+export async function wrapAccountKey(accountKey: string, unlockKey: string): Promise<string> {+ return EncryptionUtility.encryptVaultEncryptionKey(accountKey, await deriveKek(unlockKey));+}++/**+ * Unwrap the Account Key with the KEK derived from an unlock key; throws when the unlock key does not open it.+ * @param encryptedAccountKey - the wrapped Account Key+ * @param unlockKey - the unlock key (base64), the Argon2id output of the master password+ */+export async function unwrapAccountKey(encryptedAccountKey: string, unlockKey: string): Promise<string> {+ return EncryptionUtility.decryptVaultEncryptionKey(encryptedAccountKey, await deriveKek(unlockKey));+}+/*** Create a new account key hierarchy.- * @param kek - the password-derived key this account's key material is wrapped with+ * @param unlockKey - the unlock key (base64) whose derived KEK wraps this account's key material*/-export async function createAccountKeyHierarchy(kek: string): Promise<AccountKeyHierarchy> {+export async function createAccountKeyHierarchy(unlockKey: string): Promise<AccountKeyHierarchy> {const vaultEncryptionKey = EncryptionUtility.generateVaultEncryptionKey();const accountKey = EncryptionUtility.generateVaultEncryptionKey();const accountKeyPair = await EncryptionUtility.generateRsaKeyPair();@@ -33,7 +53,7 @@ export async function createAccountKeyHierarchy(kek: string): Promise<AccountKeyvaultEncryptionKey,accountPrivateKey: accountKeyPair.privateKey,accountKeys: {- encryptedAccountKey: await EncryptionUtility.encryptVaultEncryptionKey(accountKey, kek),+ encryptedAccountKey: await wrapAccountKey(accountKey, unlockKey),encryptedVek: await EncryptionUtility.encryptVaultEncryptionKey(vaultEncryptionKey, accountKey),accountPublicKey: accountKeyPair.publicKey,encryptedAccountPrivateKey: await EncryptionUtility.symmetricEncrypt(accountKeyPair.privateKey, accountKey),diff --git a/core/client/src/transfer/export/AvexExportService.ts b/core/client/src/transfer/export/AvexExportService.tsindex 6365fafd9..e9422e059 100644--- a/core/client/src/transfer/export/AvexExportService.ts+++ b/core/client/src/transfer/export/AvexExportService.ts@@ -1,4 +1,3 @@-import { DEFAULT_ENCRYPTION } from '../../auth/SrpAuthService';import { EncryptionUtility } from '../../crypto/EncryptionUtility';import { AppInfo } from '../../platform/AppInfo';import { argon2DeriveKey } from '../../rust/RustCore';@@ -13,6 +12,9 @@ import type { AvexHeader } from './AvexHeader';*/const ARGON2_KDF_PARAMS = { DegreeOfParallelism: 1, MemorySize: 262144, Iterations: 3 };+/** The KDF the export key is derived with: plain Argon2id, independent of the account's login encryption type. */+const AVEX_KDF_TYPE = 'Argon2Id';+/*** Writes the .avex encrypted vault export format: a JSON header, a PEM-style delimiter and the encrypted .avux payload* keyed with Argon2id from the export password.@@ -38,7 +40,7 @@ export class AvexExportService {const header: AvexHeader = {format: AvexConstants.FormatIdentifier,version: AvexConstants.FormatVersion,- kdf: { type: DEFAULT_ENCRYPTION.type, salt: saltBase64, params: { ...ARGON2_KDF_PARAMS } },+ kdf: { type: AVEX_KDF_TYPE, salt: saltBase64, params: { ...ARGON2_KDF_PARAMS } },encryption: { algorithm: 'AES-256-GCM', encryptedDataOffset: 0 },metadata: { exportedAt: new Date().toISOString(), exportedBy: username, appVersion: AppInfo.VERSION },};diff --git a/core/models/src/webapi/UnlockMethodType.ts b/core/models/src/webapi/UnlockMethodType.tsindex a6b9722cf..77cf7aad0 100644--- a/core/models/src/webapi/UnlockMethodType.ts+++ b/core/models/src/webapi/UnlockMethodType.ts@@ -10,7 +10,7 @@*/export const UnlockMethodType = {/**- * Master password: the KEK is derived from the password via Argon2.+ * Master password: Argon2id of the password gives the unlock key, which the KEK and SRP input are HKDF-derived from.*/Password: 'password',} as const;