Skip to content

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

Add MasterPasswordService.ts (#2159)

Leendert de Borst17c2b21c4d36
diff --git a/apps/browser-extension/src/entrypoints/background/VaultMessageHandler.ts b/apps/browser-extension/src/entrypoints/background/VaultMessageHandler.ts
index a1f176927..3ae320622 100644
--- a/apps/browser-extension/src/entrypoints/background/VaultMessageHandler.ts
+++ b/apps/browser-extension/src/entrypoints/background/VaultMessageHandler.ts
@@ -4,6 +4,7 @@ import { storage } from 'wxt/utils/storage';
import { clearAllSavePromptState } from '@/entrypoints/background/SavePromptStateHandler';
import { handleClearTwoFactorState } from '@/entrypoints/background/TwoFactorStateHandler';
+import { MasterPasswordService, PasswordChangedElsewhereError } from '@/utils/auth/MasterPasswordService';
import { base64ToBytes, bytesToBase64 } from '@/utils/Base64';
import { AUTH_STORAGE_KEYS, dirtyScopeStorageKey, SESSION_STORAGE_KEYS, StorageKeys, vaultDataStorageKeys, VAULT_LOCK_STORAGE_KEYS } from '@/utils/constants/storageKeys';
import { TRASH_RETENTION_DAYS } from '@/utils/constants/vault';
@@ -733,8 +734,7 @@ export async function handleGetEncryptionKey(
*/
export async function handleGetEncryptionKeyDerivationParams(
) : Promise<EncryptionKeyDerivationParams | null> {
- // Get metadata from storage
- return await getStorageItem<EncryptionKeyDerivationParams>(StorageKeys.ENCRYPTION_KEY_DERIVATION_PARAMS);
+ return MasterPasswordService.getStoredDerivationParams();
}
/**
@@ -1627,11 +1627,8 @@ async function runSyncPreflight(webApi: WebApiService, options?: FullVaultSyncOp
return abortSync({ success: false, requiresLogout, errorKey: statusError });
}
- // A changed SRP salt means the password was changed on another device (this device's own change holds the sync hold).
- const storedEncryptionParams = await handleGetEncryptionKeyDerivationParams();
- if (storedEncryptionParams && statusResponse.srpSalt && statusResponse.srpSalt !== storedEncryptionParams.salt) {
- return abortSync({ success: false, requiresLogout: true, errorKey: 'passwordChanged' });
- }
+ // Verify that the server's salt still matches the one this device derived its keys from, if not, it indicates password was changed remotely which warrants a logout.
+ await MasterPasswordService.assertSaltUnchanged(statusResponse.srpSalt);
/*
* Only needed when we are about to pull: the vault data below is decrypted with the session key, which is stale if
@@ -2180,6 +2177,11 @@ async function mapSyncFailure(err: unknown): Promise<FullVaultSyncResult> {
return syncResult({ success: false, requiresLogout: true, errorKey: 'sessionExpired' });
}
+ // The password was changed on another device: this device's keys no longer match, so it has to log in again.
+ if (err instanceof PasswordChangedElsewhereError) {
+ return syncResult({ success: false, requiresLogout: true, errorKey: 'passwordChanged' });
+ }
+
// E-805: Vault transfer timed out - show a targeted error instead of entering offline mode
if (err instanceof RequestTimeoutError) {
return syncResult({ success: false, error: formatErrorWithCode(await t('common.errors.vaultSyncTimeout'), AppErrorCode.UPLOAD_TIMEOUT) });
diff --git a/apps/browser-extension/src/entrypoints/popup/pages/settings/security/ChangePasswordSettings.tsx b/apps/browser-extension/src/entrypoints/popup/pages/settings/security/ChangePasswordSettings.tsx
index ef934cddd..b571094df 100644
--- a/apps/browser-extension/src/entrypoints/popup/pages/settings/security/ChangePasswordSettings.tsx
+++ b/apps/browser-extension/src/entrypoints/popup/pages/settings/security/ChangePasswordSettings.tsx
@@ -11,7 +11,7 @@ import { useLoading } from '@/entrypoints/popup/context/LoadingContext';
import { useWebApi } from '@/entrypoints/popup/context/WebApiContext';
import { useVaultSync } from '@/entrypoints/popup/hooks/useVaultSync';
-import { CurrentPasswordIncorrectError, PasswordChangedElsewhereError, PasswordChangeService } from '@/utils/auth/PasswordChangeService';
+import { IncorrectPasswordError, MasterPasswordService, PasswordChangedElsewhereError } from '@/utils/auth/MasterPasswordService';
import { ApiRequestError } from '@/utils/types/errors/ApiRequestError';
type PasswordInputProps = {
@@ -87,7 +87,7 @@ const ChangePasswordSettings: React.FC = () => {
* @param err - the error thrown by the change flow
*/
const errorMessage = (err: unknown): string => {
- if (err instanceof CurrentPasswordIncorrectError) {
+ if (err instanceof IncorrectPasswordError) {
return t('common.errors.wrongPassword');
}
if (err instanceof PasswordChangedElsewhereError) {
@@ -123,7 +123,7 @@ const ChangePasswordSettings: React.FC = () => {
try {
showLoading();
- await PasswordChangeService.changePassword(webApi, currentPassword, newPassword);
+ await MasterPasswordService.changePassword(webApi, currentPassword, newPassword);
setCurrentPassword('');
setNewPassword('');
setConfirmPassword('');
diff --git a/apps/browser-extension/src/utils/SharingService.ts b/apps/browser-extension/src/utils/SharingService.ts
index 144235d0c..18b0d2706 100644
--- a/apps/browser-extension/src/utils/SharingService.ts
+++ b/apps/browser-extension/src/utils/SharingService.ts
@@ -1,6 +1,6 @@
import { storage } from 'wxt/utils/storage';
-import { SrpAuthService } from '@/utils/auth/SrpAuthService';
+import { MasterPasswordService } from '@/utils/auth/MasterPasswordService';
import { StorageKeys } from '@/utils/constants/storageKeys';
import { devWarn } from '@/utils/devLogger/DevLogger';
import { VaultKeyAlgorithm, type CreateSharedManifestRequest, type CreateSharedManifestResponse, type DeleteSharedManifestInitiateResponse, type DeleteSharedManifestRequest, type GrantManifestAccessRequest, type GrantManifestAccessResponse, type GroupMemberInfo, type GroupOverviewResponse, type ManifestGrant, type ReceivedManifestInvitation, type VaultKeyAlgorithmValue } from '@/utils/dist/core/models/webapi';
@@ -171,9 +171,8 @@ export class SharingService {
* @param password - the caller's master password, proven to the server and forgotten.
*/
public static async deleteSharedManifest(webApi: WebApiService, groupId: string, manifestId: string, password: string): Promise<void> {
- const initiate = await webApi.post<object, DeleteSharedManifestInitiateResponse>(`Groups/${groupId}/manifests/${manifestId}/delete/initiate`, {});
- const { passwordHashString } = await SrpAuthService.prepareCredentials(password, initiate.salt, initiate.encryptionSettings);
- const proof = await SrpAuthService.deriveClientProof(initiate.salt, initiate.srpIdentity, passwordHashString, initiate.serverEphemeral);
+ const challenge = await webApi.post<object, DeleteSharedManifestInitiateResponse>(`Groups/${groupId}/manifests/${manifestId}/delete/initiate`, {});
+ const { proof } = await MasterPasswordService.answerSrpChallenge(challenge, password);
await webApi.post<DeleteSharedManifestRequest, void>(`Groups/${groupId}/manifests/${manifestId}/delete/confirm`, proof, false);
}
diff --git a/apps/browser-extension/src/utils/VaultKeyService.ts b/apps/browser-extension/src/utils/VaultKeyService.ts
index 745d39c8b..cca08e054 100644
--- a/apps/browser-extension/src/utils/VaultKeyService.ts
+++ b/apps/browser-extension/src/utils/VaultKeyService.ts
@@ -5,6 +5,7 @@
import { storage } from 'wxt/utils/storage';
import { StorageKeys } from '@/utils/constants/storageKeys';
+import type { EncryptionKeyDerivationParams } from '@/utils/dist/core/models/metadata';
import { UnlockMethodType, type VaultKeyGetResponse, type VaultKeyResponse } from '@/utils/dist/core/models/webapi';
import { EncryptionUtility } from '@/utils/EncryptionUtility';
import { ApiRequestError } from '@/utils/types/errors/ApiRequestError';
@@ -134,6 +135,18 @@ export class VaultKeyService {
]);
}
+ /**
+ * Persist new account key after a local password change.
+ * @param newEncryptedAccountKey - the Account Key encrypted with the new password-derived KEK
+ * @param derivationParams - the KEK derivation parameters of the new password
+ */
+ public static async persistNewAccountKey(newEncryptedAccountKey: string, derivationParams: EncryptionKeyDerivationParams): Promise<void> {
+ await storage.setItems([
+ { key: StorageKeys.ENCRYPTED_ACCOUNT_KEY, value: newEncryptedAccountKey },
+ { key: StorageKeys.ENCRYPTION_KEY_DERIVATION_PARAMS, value: derivationParams },
+ ]);
+ }
+
/**
* Resolve the key to actually use for a local additional unlock method (PIN, mobile QR), upgrading a pre-migration
* stored key (the old KEK) to the VEK when needed.
diff --git a/apps/browser-extension/src/utils/auth/MasterPasswordService.ts b/apps/browser-extension/src/utils/auth/MasterPasswordService.ts
new file mode 100644
index 000000000..6505befd1
--- /dev/null
+++ b/apps/browser-extension/src/utils/auth/MasterPasswordService.ts
@@ -0,0 +1,174 @@
+import { storage } from 'wxt/utils/storage';
+
+import { StorageKeys } from '@/utils/constants/storageKeys';
+import type { EncryptionKeyDerivationParams } from '@/utils/dist/core/models/metadata';
+import type { PasswordChangeInitiateResponse, PasswordChangeRequest } from '@/utils/dist/core/models/webapi';
+import { EncryptionUtility } from '@/utils/EncryptionUtility';
+import { getStorageItem } from '@/utils/StorageUtility';
+import { VaultKeyService } from '@/utils/VaultKeyService';
+import { VaultSyncHoldReason, withVaultSyncHold } from '@/utils/VaultSyncHold';
+import type { WebApiService } from '@/utils/WebApiService';
+
+import { SrpAuthService, type SrpClientProof } from './SrpAuthService';
+
+/**
+ * Thrown when the entered master password does not decrypt the Account Key.
+ */
+export class IncorrectPasswordError extends Error {
+ /** Creates the error. */
+ public constructor() {
+ super('Master password is incorrect');
+ this.name = 'IncorrectPasswordError';
+ Object.setPrototypeOf(this, IncorrectPasswordError.prototype);
+ }
+}
+
+/**
+ * Thrown when the server's salt no longer matches the stored one which indicates that the master password was changed (on another device).
+ */
+export class PasswordChangedElsewhereError extends Error {
+ /** Creates the error. */
+ public constructor() {
+ super('Password was changed on another device');
+ this.name = 'PasswordChangedElsewhereError';
+ Object.setPrototypeOf(this, PasswordChangedElsewhereError.prototype);
+ }
+}
+
+/** The SRP challenge a server endpoint issues before it accepts a password-confirmed action. */
+export type SrpChallenge = {
+ salt: string;
+ serverEphemeral: string;
+ encryptionSettings: string;
+ srpIdentity?: string;
+};
+
+/** The answer to an SRP challenge, plus what the same derivation yields for local key material. */
+export type SrpChallengeAnswer = {
+ proof: SrpClientProof;
+ kekBase64: string;
+ srpIdentity: string;
+};
+
+/**
+ * MasterPasswordService handling all master password operations.
+ */
+export class MasterPasswordService {
+ /**
+ * The derivation parameters of the password this device holds, or null before the first online unlock.
+ */
+ public static async getStoredDerivationParams(): Promise<EncryptionKeyDerivationParams | null> {
+ return getStorageItem<EncryptionKeyDerivationParams>(StorageKeys.ENCRYPTION_KEY_DERIVATION_PARAMS);
+ }
+
+ /**
+ * Sanity check that a salt the server reports is still the one this device derived its keys from. Unknown on
+ * either side passes: there is nothing to compare yet.
+ * @param serverSalt - the salt the server currently holds for this account
+ * @throws {PasswordChangedElsewhereError} when the salts differ: the password was changed on another device.
+ */
+ public static async assertSaltUnchanged(serverSalt: string | null | undefined): Promise<void> {
+ const stored = await MasterPasswordService.getStoredDerivationParams();
+ if (stored && serverSalt && serverSalt !== stored.salt) {
+ throw new PasswordChangedElsewhereError();
+ }
+ }
+
+ /**
+ * 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.
+ * @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);
+
+ /*
+ * Use srpIdentity from the challenge if available, otherwise fall back to the normalized username.
+ * @todo Remove fallback after 0.26.0+ has been released.
+ */
+ const username = (await storage.getItem(StorageKeys.USERNAME)) as string | null;
+ 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 };
+ }
+
+ /**
+ * 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
+ * @returns The decrypted Account Key and its new wrapping.
+ * @throws {IncorrectPasswordError} when the old KEK 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) };
+ }
+
+ /**
+ * Change the master password by re-encrypting the Account Key using a new KEK.
+ * @param webApi - the API client to use
+ * @param currentPassword - the current master password
+ * @param newPassword - the new master password
+ * @throws {IncorrectPasswordError} when the current password is wrong (detected locally).
+ * @throws {PasswordChangedElsewhereError} when the password was already changed on another device.
+ * @throws {ApiRequestError} when the server rejects the change (e.g. PASSWORD_MISMATCH on a concurrent change).
+ */
+ public static async changePassword(webApi: WebApiService, currentPassword: string, newPassword: string): Promise<void> {
+ // Hold the vault sync to prevent concurrent password changes.
+ await withVaultSyncHold(VaultSyncHoldReason.PasswordChange, () => MasterPasswordService.performChange(webApi, currentPassword, newPassword));
+ }
+
+ /**
+ * Change master password: verify the current password, re-encrypt the Account Key, commit on the server, persist locally.
+ * @param webApi - the API client to use
+ * @param currentPassword - the current master password
+ * @param newPassword - the new master password
+ */
+ private static async performChange(webApi: WebApiService, currentPassword: string, newPassword: string): Promise<void> {
+ const storedParams = await MasterPasswordService.getStoredDerivationParams();
+ const encryptedAccountKey = (await storage.getItem(StorageKeys.ENCRYPTED_ACCOUNT_KEY)) as string | null;
+ if (!storedParams || !encryptedAccountKey) {
+ throw new Error('Password change requires an unlocked account-key vault');
+ }
+
+ const challenge = await webApi.get<PasswordChangeInitiateResponse>('Auth/change-password/initiate');
+ await MasterPasswordService.assertSaltUnchanged(challenge.salt);
+
+ 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);
+
+ await webApi.post<PasswordChangeRequest, void>('Auth/change-password', {
+ currentClientPublicEphemeral: current.proof.clientPublicEphemeral,
+ currentClientSessionProof: current.proof.clientSessionProof,
+ newPasswordSalt: next.salt,
+ newPasswordVerifier: next.verifier,
+ newEncryptedAccountKey,
+ newEncryptionType: next.encryptionType,
+ newEncryptionSettings: next.encryptionSettings,
+ }, false);
+
+ // Persist the new Account Key and its derivation parameters.
+ await VaultKeyService.persistNewAccountKey(newEncryptedAccountKey, { salt: next.salt, encryptionType: next.encryptionType, encryptionSettings: next.encryptionSettings });
+ }
+
+ /**
+ * 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
+ */
+ private static async decryptAccountKey(encryptedAccountKey: string, kekBase64: string): Promise<string> {
+ try {
+ return await EncryptionUtility.decryptVaultEncryptionKey(encryptedAccountKey, kekBase64);
+ } catch {
+ throw new IncorrectPasswordError();
+ }
+ }
+}
+
+export default MasterPasswordService;
diff --git a/apps/browser-extension/src/utils/auth/SrpAuthService.ts b/apps/browser-extension/src/utils/auth/SrpAuthService.ts
index 13053e6e6..69b217ed3 100644
--- a/apps/browser-extension/src/utils/auth/SrpAuthService.ts
+++ b/apps/browser-extension/src/utils/auth/SrpAuthService.ts
@@ -20,9 +20,7 @@ export type RegisterRequest = {
verifier: string;
encryptionType: string;
encryptionSettings: string;
- /** The SRP identity used for authentication (a random GUID generated at registration). */
srpIdentity: string;
- /** The encrypted VEK (KEK/VEK model): base64 of the freshly generated VEK encrypted with the password-derived KEK. */
encryptedVek: string;
};
@@ -31,9 +29,7 @@ export type RegisterRequest = {
*/
export type PreparedRegistration = {
request: RegisterRequest;
- /** The generated VEK (base64): the vault encryption key to store in session after successful registration. */
vaultEncryptionKey: string;
- /** The password-derived key (base64): the KEK, only needed for key encryption/SRP, never for vault content. */
derivedKey: string;
};
@@ -43,9 +39,7 @@ export type PreparedRegistration = {
export type RegistrationResult = {
success: boolean;
token?: TokenModel;
- /** The vault encryption key (VEK, base64) to use for all vault encryption after successful registration. */
encryptionKey?: string;
- /** The encrypted VEK to cache locally for offline unlock. */
encryptedVek?: string;
error?: string;
};
@@ -62,12 +56,21 @@ export type SrpClientProof = {
* Login credentials prepared from password derivation.
*/
export type PreparedCredentials = {
- /** Password hash as uppercase hex string for SRP */
passwordHashString: string;
- /** Password hash as base64 string for encryption/decryption */
passwordHashBase64: string;
};
+/**
+ * What a new master password needs on both sides: what the server stores to verify it, and the KEK it derives.
+ */
+export type NewPasswordMaterial = {
+ salt: string;
+ verifier: string;
+ encryptionType: string;
+ encryptionSettings: string;
+ kekBase64: string;
+};
+
/**
* Default encryption settings for Argon2Id.
* These match the server defaults in AliasVault.Cryptography.Client/Defaults.cs
@@ -335,6 +338,20 @@ export class SrpAuthService {
return crypto.randomUUID();
}
+ /**
+ * Derive what a new master password needs: a fresh salt, the SRP verifier the server stores, and the KEK the
+ * client wraps its key material with. Uses the default Argon2Id settings.
+ * @param password - the new master password
+ * @param srpIdentity - the account's SRP identity the verifier is bound to
+ */
+ public static async prepareNewPassword(password: string, srpIdentity: string): Promise<NewPasswordMaterial> {
+ const salt = await SrpAuthService.generateSalt();
+ const credentials = await SrpAuthService.prepareCredentials(password, salt, DEFAULT_ENCRYPTION.settings);
+ const privateKey = await SrpAuthService.derivePrivateKey(salt, srpIdentity, credentials.passwordHashString);
+ const verifier = await SrpAuthService.deriveVerifier(privateKey);
+ return { salt, verifier, encryptionType: DEFAULT_ENCRYPTION.type, encryptionSettings: DEFAULT_ENCRYPTION.settings, kekBase64: credentials.passwordHashBase64 };
+ }
+
/**
* Prepares SRP registration data for a new user.
*
@@ -352,40 +369,33 @@ export class SrpAuthService {
password: string
): Promise<PreparedRegistration> {
const normalizedUsername = SrpAuthService.normalizeUsername(username);
- const salt = await SrpAuthService.generateSalt();
/**
* Generate a random GUID for SRP identity. This is used for all SRP operations,
* is set during registration, and never changes.
*/
const srpIdentity = SrpAuthService.generateSrpIdentity();
-
- // Derive key from password using default Argon2Id settings
- const credentials = await SrpAuthService.prepareCredentials(password, salt, DEFAULT_ENCRYPTION.settings);
-
- // Generate SRP private key and verifier using srpIdentity (not username)
- const privateKey = await SrpAuthService.derivePrivateKey(salt, srpIdentity, credentials.passwordHashString);
- const verifier = await SrpAuthService.deriveVerifier(privateKey);
+ const material = await SrpAuthService.prepareNewPassword(password, srpIdentity);
/*
* KEK/VEK: generate a random VEK that will encrypt the vault content, encrypted with the password-derived KEK.
* The server stores only the encrypted form; the VEK itself stays client-side.
*/
const vaultEncryptionKey = EncryptionUtility.generateVaultEncryptionKey();
- const encryptedVek = await EncryptionUtility.encryptVaultEncryptionKey(vaultEncryptionKey, credentials.passwordHashBase64);
+ const encryptedVek = await EncryptionUtility.encryptVaultEncryptionKey(vaultEncryptionKey, material.kekBase64);
return {
request: {
username: normalizedUsername,
- salt,
- verifier,
- encryptionType: DEFAULT_ENCRYPTION.type,
- encryptionSettings: DEFAULT_ENCRYPTION.settings,
+ salt: material.salt,
+ verifier: material.verifier,
+ encryptionType: material.encryptionType,
+ encryptionSettings: material.encryptionSettings,
srpIdentity,
encryptedVek,
},
vaultEncryptionKey,
- derivedKey: credentials.passwordHashBase64,
+ derivedKey: material.kekBase64,
};
}