Privacy-first password manager with built-in email aliasing. Fully encrypted and self-hostable.
Add UnlockService.ts helper (#2468)
Leendert de Borstd67cdf0fd32c
diff --git a/apps/browser-extension/src/entrypoints/background/AuthHandler.ts b/apps/browser-extension/src/entrypoints/background/AuthHandler.tsindex 6b9ffb367..eb5ca7208 100644--- a/apps/browser-extension/src/entrypoints/background/AuthHandler.ts+++ b/apps/browser-extension/src/entrypoints/background/AuthHandler.ts@@ -6,11 +6,12 @@ import { WebApiService } from '@aliasvault/client/api/WebApiService';import { describeAuthError, type AuthErrorOptions } from '@aliasvault/client/auth/AuthErrorMessage';import { SrpAuthService } from '@aliasvault/client/auth/SrpAuthService';import { SrpLoginService } from '@aliasvault/client/auth/SrpLoginService';+import { MissingDerivationParamsError, UnlockService } from '@aliasvault/client/auth/UnlockService';import { VaultKeyService } from '@aliasvault/client/auth/VaultKeyService';import { logoutReasonKey } from '@aliasvault/client/sync/VaultSync';import { handleClearTwoFactorState, handleGetTwoFactorState, handleStoreTwoFactorState } from '@/entrypoints/background/TwoFactorStateHandler';-import { handleClearSession, handleFullVaultSync, handleGetUnlockKeyDerivationParams, handleStoreAccountKey, handleStoreUnlockKeyDerivationParams } from '@/entrypoints/background/VaultMessageHandler';+import { handleClearSession, handleFullVaultSync, handleStoreAccountKey } from '@/entrypoints/background/VaultMessageHandler';import { StorageKeys } from '@/utils/constants/storageKeys';import { logExpected, logFailure } from '@/utils/Diagnostics';@@ -133,6 +134,13 @@ async function storeAccountKey(accountKey: string, offline: boolean, broadcast:throw new Error(stored.error);}+ await markUnlocked(offline, broadcast);+}++/**+ * Record the unlocked state next to a stored Account Key, and tell content scripts about it when asked.+ */+async function markUnlocked(offline: boolean, broadcast: boolean): Promise<void> {await storage.setItem(StorageKeys.IS_OFFLINE_MODE, offline);await LocalPreferencesService.setVaultLockedDismissUntil(0);if (broadcast) {@@ -152,32 +160,18 @@ export function handleUnlockWithPassword(data: { password: string }): Promise<Ba}try {- let accountKey: string;- if (status.online) {- const username = await storage.getItem<string>(StorageKeys.USERNAME);- const loginResponse = await new SrpLoginService(webApi).initiateLogin(username!);- const unlockKey = await SrpAuthService.deriveUnlockKey(data.password, loginResponse.salt, 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.- accountKey = await VaultKeyService.refreshKeyChain(unlockKey, webApi);- } else {- const storedParams = await handleGetUnlockKeyDerivationParams();- if (!storedParams) {- // Offline unlock needs the derivation params of an earlier online login.- return { status: 'error', error: { key: 'common.errors.serverNotAvailable', wrongPassword: false } };- }-- const unlockKey = await SrpAuthService.deriveUnlockKey(data.password, storedParams.salt, storedParams.encryptionSettings);- accountKey = await VaultKeyService.verifyUnlockKey(unlockKey);- }-+ // Throws an unlock-key-rejected (E-206) error on a wrong password.+ const accountKey = await UnlockService.unlockWithPassword(data.password, { online: status.online, webApi });await storeAccountKey(accountKey, status.offline, true);await resetFailedAttempts();await LocalPreferencesService.resetPasswordUnlockFailedAttempts();await LocalPreferencesService.setLastUsedUnlockMethod('password');return { status: 'success', offline: status.offline };} catch (err) {+ if (err instanceof MissingDerivationParamsError) {+ // Offline unlock needs the derivation params of an earlier online login.+ return { status: 'error', error: { key: 'common.errors.serverNotAvailable', wrongPassword: false } };+ }const message = await describeAuthError(err, { uncodedIsWrongPassword: true });if (message.wrongPassword) {const failedAttempts = await LocalPreferencesService.getPasswordUnlockFailedAttempts() + 1;@@ -298,19 +292,13 @@ 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 accountKey: string;- try {- accountKey = await VaultKeyService.refreshKeyChain(unlockKey, webApi);- } catch (err) {+ await UnlockService.completeKeyChainLogin(unlockKey, derivationParams, webApi, async () => {await webApi.revokeTokens();await handleClearSession();- throw err;- }-- await 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 storeAccountKey(accountKey, false, false);+ await markUnlocked(false, false);const sync = await handleFullVaultSync({ forcePull: true, reportErrorToPopup: false });if (sync.logoutReason === 'clientVersionNotSupported') {diff --git a/apps/server/AliasVault.Admin/wwwroot/css/tailwind.css b/apps/server/AliasVault.Admin/wwwroot/css/tailwind.cssindex 298071916..13a793bf1 100644--- a/apps/server/AliasVault.Admin/wwwroot/css/tailwind.css+++ b/apps/server/AliasVault.Admin/wwwroot/css/tailwind.css@@ -693,10 +693,6 @@ video {margin-bottom: 1rem;}-.-mb-2 {- margin-bottom: -0.5rem;-}-.mb-1 {margin-bottom: 0.25rem;}@@ -793,6 +789,10 @@ video {margin-top: 2rem;}+.-mb-2 {+ margin-bottom: -0.5rem;+}+.line-clamp-1 {overflow: hidden;display: -webkit-box;@@ -1109,10 +1109,6 @@ video {gap: 0.5rem;}-.gap-3 {- gap: 0.75rem;-}-.gap-4 {gap: 1rem;}@@ -1121,6 +1117,10 @@ video {gap: 1.5rem;}+.gap-3 {+ gap: 0.75rem;+}+.space-x-1 > :not([hidden]) ~ :not([hidden]) {--tw-space-x-reverse: 0;margin-right: calc(0.25rem * var(--tw-space-x-reverse));@@ -1485,10 +1485,6 @@ video {fill: #d68338;}-.p-1 {- padding: 0.25rem;-}-.p-2 {padding: 0.5rem;}@@ -1513,6 +1509,10 @@ video {padding: 1.5rem;}+.p-1 {+ padding: 0.25rem;+}+.px-1 {padding-left: 0.25rem;padding-right: 0.25rem;diff --git a/apps/web/src/pages/auth/Login.tsx b/apps/web/src/pages/auth/Login.tsxindex 525c4f9a4..258802f07 100644--- a/apps/web/src/pages/auth/Login.tsx+++ b/apps/web/src/pages/auth/Login.tsx@@ -2,7 +2,7 @@ import { extractErrorCode } from '@aliasvault/client/api/errors/AppErrorCodes';import { describeAuthError, formatErrorMessage } from '@aliasvault/client/auth/AuthErrorMessage';import { SrpAuthService, type PreparedCredentials } from '@aliasvault/client/auth/SrpAuthService';import { SrpLoginService } from '@aliasvault/client/auth/SrpLoginService';-import { VaultKeyService } from '@aliasvault/client/auth/VaultKeyService';+import { UnlockService } from '@aliasvault/client/auth/UnlockService';import { getPlatform } from '@aliasvault/client/platform';import React, { useEffect, useMemo, useRef, useState } from 'react';import { useTranslation } from 'react-i18next';@@ -26,7 +26,6 @@ import { usePageTitle } from '@/hooks/usePageTitle';import { asksForClientUpdate, updateApp } from '@/utils/ClientUpdate';import { focusWhenVisible } from '@/utils/FocusWhenVisible';import { StorageKeys } from '@/utils/StorageKeys';-import { vaultStore } from '@/vault/VaultStore';import type { MobileLoginResult } from '@aliasvault/client/auth/MobileLoginService';import type { UnlockKeyDerivationParams } from '@aliasvault/models/metadata';@@ -117,17 +116,8 @@ const Login: React.FC = () => {try {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 accountKey: string;- try {- accountKey = 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.storeAccountKey(accountKey);+ // Fetch the key chain, check the unlock key opens it and cache it; without a usable chain the session is useless, so end it.+ await UnlockService.completeKeyChainLogin(unlockKey, params, webApi, () => auth.logout());notifications.clearMessages();navigate('/sync', { replace: true });@@ -157,7 +147,7 @@ const Login: React.FC = () => {try {const params = { salt: result.salt, encryptionType: result.encryptionType, encryptionSettings: result.encryptionSettings };- await completeLogin(result.username, result.token, result.refreshToken, result.unlockKey, params);+ await completeLogin(result.username, result.token, result.refreshToken, result.accountKey, params);} 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 71fb3c72f..62a346183 100644--- a/apps/web/src/pages/auth/Unlock.tsx+++ b/apps/web/src/pages/auth/Unlock.tsx@@ -2,12 +2,9 @@ import { ApiAuthError } from '@aliasvault/client/api/errors/ApiAuthError';import { extractErrorCode } from '@aliasvault/client/api/errors/AppErrorCodes';import { ClientUpgradeRequiredError } from '@aliasvault/client/api/errors/ClientUpgradeRequiredError';import { describeAuthError, formatErrorMessage } from '@aliasvault/client/auth/AuthErrorMessage';-import { MasterPasswordService } from '@aliasvault/client/auth/MasterPasswordService';-import { SrpAuthService } from '@aliasvault/client/auth/SrpAuthService';-import { SrpLoginService } from '@aliasvault/client/auth/SrpLoginService';-import { VaultKeyService } from '@aliasvault/client/auth/VaultKeyService';+import { MissingDerivationParamsError, UnlockService } from '@aliasvault/client/auth/UnlockService';import { logoutReasonKey } from '@aliasvault/client/sync/VaultSync';-import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react';+import React, { useCallback, useEffect, useRef, useState } from 'react';import { useTranslation } from 'react-i18next';import { Link, useNavigate, useParams } from 'react-router-dom';@@ -43,7 +40,6 @@ const Unlock: React.FC = () => {const webApi = useWebApi();const notifications = useNotifications();const { showLoading, hideLoading } = useLoading();- const srpUtil = useMemo(() => new SrpLoginService(webApi), [webApi]);usePageTitle(t('auth.unlockPage.unlockButton'));const { skipWebAuthn } = useParams<{ skipWebAuthn?: string }>();@@ -161,26 +157,13 @@ const Unlock: React.FC = () => {setErrors([]);try {- let accountKey: string;- if (dbContext.getIsOffline()) {- const params = await MasterPasswordService.getStoredDerivationParams();- if (!params) {- throw new Error(t('auth.unlockPage.connectionFailedError'));- }- const unlockKey = await SrpAuthService.deriveUnlockKey(password, params.salt, params.encryptionSettings);- // Throws an unlock-key-rejected (E-206) error on a wrong password.- accountKey = await VaultKeyService.verifyUnlockKey(unlockKey);- } else {- const loginResponse = await srpUtil.initiateLogin(username);- const unlockKey = await SrpAuthService.deriveUnlockKey(password, loginResponse.salt, loginResponse.encryptionSettings);- await vaultStore.storeUnlockKeyDerivationParams({ salt: loginResponse.salt, encryptionType: loginResponse.encryptionType, encryptionSettings: loginResponse.encryptionSettings });- // Throws an unlock-key-rejected (E-206) error on a wrong password.- accountKey = await VaultKeyService.refreshKeyChain(unlockKey, webApi);- }-+ // Throws an unlock-key-rejected (E-206) error on a wrong password.+ const accountKey = await UnlockService.unlockWithPassword(password, { online: !dbContext.getIsOffline(), webApi, username });await vaultStore.storeAccountKey(accountKey);navigate('/sync', { replace: true });- } catch (err) {+ } catch (caught) {+ // Offline unlock needs the derivation params of an earlier online login.+ const err = caught instanceof MissingDerivationParamsError ? new Error(t('auth.unlockPage.connectionFailedError')) : caught;console.error('Unlock error:', err);if (err instanceof ApiAuthError) {navigate('/user/login', { replace: true });@@ -217,9 +200,7 @@ 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.- const accountKey = await VaultKeyService.refreshKeyChain(result.unlockKey, webApi);- await vaultStore.storeUnlockKeyDerivationParams({ salt: result.salt, encryptionType: result.encryptionType, encryptionSettings: result.encryptionSettings });- await vaultStore.storeAccountKey(accountKey);+ await UnlockService.completeKeyChainLogin(result.accountKey, result, webApi);navigate('/sync', { replace: true });} catch (err) {console.error('Mobile unlock error:', err);diff --git a/apps/web/src/utils/MasterPasswordCheck.ts b/apps/web/src/utils/MasterPasswordCheck.tsindex 94ac88766..415e1ad72 100644--- a/apps/web/src/utils/MasterPasswordCheck.ts+++ b/apps/web/src/utils/MasterPasswordCheck.ts@@ -1,6 +1,5 @@import { extractErrorCode } from '@aliasvault/client/api/errors/AppErrorCodes';-import { MasterPasswordService } from '@aliasvault/client/auth/MasterPasswordService';-import { SrpAuthService } from '@aliasvault/client/auth/SrpAuthService';+import { MissingDerivationParamsError, UnlockService } from '@aliasvault/client/auth/UnlockService';import { VaultKeyService } from '@aliasvault/client/auth/VaultKeyService';/**@@ -10,16 +9,17 @@ import { VaultKeyService } from '@aliasvault/client/auth/VaultKeyService';* @throws Error when the check itself cannot run (no stored derivation parameters or key chain).*/export async function verifyMasterPassword(password: string): Promise<boolean> {- const params = await MasterPasswordService.getStoredDerivationParams();- if (!params || !await VaultKeyService.hasLocalVaultKey()) {+ if (!await VaultKeyService.hasLocalVaultKey()) {throw new Error('No local key chain to verify the master password against');}- const unlockKey = await SrpAuthService.deriveUnlockKey(password, params.salt, params.encryptionSettings);try {- await VaultKeyService.verifyUnlockKey(unlockKey);+ await UnlockService.verifyPasswordOffline(password);return true;} catch (error) {+ if (error instanceof MissingDerivationParamsError) {+ throw new Error('No local key chain to verify the master password against');+ }const code = error instanceof Error ? extractErrorCode(error.message) : null;if (await VaultKeyService.isWrongUnlockKey(code)) {return false;diff --git a/core/client/src/auth/UnlockService.ts b/core/client/src/auth/UnlockService.tsnew file mode 100644index 000000000..93676d190--- /dev/null+++ b/core/client/src/auth/UnlockService.ts@@ -0,0 +1,110 @@+import { StorageKeys } from '../constants/StorageKeys';+import { getPlatform } from '../platform/ClientPlatform';++import { MasterPasswordService } from './MasterPasswordService';+import { SrpAuthService } from './SrpAuthService';+import { SrpLoginService } from './SrpLoginService';+import { VaultKeyService } from './VaultKeyService';++import type { WebApiService } from '../api/WebApiService';+import type { UnlockKeyDerivationParams } from '@aliasvault/models/metadata';++/**+ * Thrown by an offline password check when this device holds no derivation parameters from an earlier online login.+ */+export class MissingDerivationParamsError extends Error {+ /** Creates the error. */+ public constructor() {+ super('No stored unlock key derivation parameters');+ this.name = 'MissingDerivationParamsError';+ Object.setPrototypeOf(this, MissingDerivationParamsError.prototype);+ }+}++/** How {@link UnlockService.unlockWithPassword} reaches the server. */+export type PasswordUnlockOptions = {+ /** Unlock against the server's key chain (true) or the locally cached one (false). */+ online: boolean;+ /** The API client, required when online. */+ webApi?: WebApiService;+ /** The account to unlock; defaults to the stored username. */+ username?: string;+};++/**+ * The master password unlock and login completion flows, shared by every host.+ */+export class UnlockService {+ /**+ * Check a master password offline: stored derivation parameters, derive the unlock key, open the cached key chain.+ * @param password - the master password+ * @returns The Account Key.+ * @throws {MissingDerivationParamsError} when no derivation parameters are stored.+ * @throws Error with AppErrorCode.UNLOCK_KEY_REJECTED (E-206) on a wrong password.+ */+ public static async verifyPasswordOffline(password: string): Promise<string> {+ const params = await MasterPasswordService.getStoredDerivationParams();+ if (!params) {+ throw new MissingDerivationParamsError();+ }++ const unlockKey = await SrpAuthService.deriveUnlockKey(password, params.salt, params.encryptionSettings);+ return VaultKeyService.verifyUnlockKey(unlockKey);+ }++ /**+ * Unlock with the master password, online against the server's key chain or offline against the cached one. The+ * caller stores the returned Account Key.+ * @param password - the master password+ * @param options - online or offline, and the API client for the online path+ * @returns The Account Key.+ * @throws {MissingDerivationParamsError} offline, when no derivation parameters are stored.+ * @throws Error with AppErrorCode.UNLOCK_KEY_REJECTED (E-206) on a wrong password.+ */+ public static async unlockWithPassword(password: string, options: PasswordUnlockOptions): Promise<string> {+ if (!options.online) {+ return UnlockService.verifyPasswordOffline(password);+ }+ if (!options.webApi) {+ throw new Error('An online unlock needs an API client');+ }++ const username = options.username ?? await getPlatform().storage.get<string>(StorageKeys.USERNAME);+ const loginResponse = await new SrpLoginService(options.webApi).initiateLogin(username!);+ const unlockKey = await SrpAuthService.deriveUnlockKey(password, loginResponse.salt, loginResponse.encryptionSettings);+ await UnlockService.storeDerivationParams(loginResponse);+ return VaultKeyService.refreshKeyChain(unlockKey, options.webApi);+ }++ /**+ * Finish an accepted login: fetch and check the key chain, then store the derivation parameters and the Account Key.+ * @param unlockKeyBase64 - the unlock key of the login, or the Account Key a mobile app sent+ * @param derivationParams - the derivation parameters of the account's password+ * @param webApi - the API client, already holding the new session's tokens+ * @param onKeyChainFailure - ends the session when the key chain cannot be opened, before the error is rethrown+ * @returns The Account Key.+ */+ public static async completeKeyChainLogin(unlockKeyBase64: string, derivationParams: UnlockKeyDerivationParams, webApi: WebApiService, onKeyChainFailure?: () => Promise<void>): Promise<string> {+ let accountKey: string;+ try {+ accountKey = await VaultKeyService.refreshKeyChain(unlockKeyBase64, webApi);+ } catch (err) {+ await onKeyChainFailure?.();+ throw err;+ }++ await UnlockService.storeDerivationParams(derivationParams);+ await getPlatform().storage.set(StorageKeys.ACCOUNT_KEY, accountKey);+ return accountKey;+ }++ /**+ * Store the derivation parameters for offline unlock and local password checks.+ */+ private static async storeDerivationParams(params: UnlockKeyDerivationParams): Promise<void> {+ const { salt, encryptionType, encryptionSettings } = params;+ await getPlatform().storage.set(StorageKeys.UNLOCK_KEY_DERIVATION_PARAMS, { salt, encryptionType, encryptionSettings });+ }+}++export default UnlockService;