Skip to content

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

Move TOTP, Srp and password slider helper logic to core/client (#2159)

Leendert de Borst91c8e00d9f86
diff --git a/apps/browser-extension/src/entrypoints/popup/components/Forms/PasswordConfigForm.tsx b/apps/browser-extension/src/entrypoints/popup/components/Forms/PasswordConfigForm.tsx
index 803124d48..4130344bf 100644
--- a/apps/browser-extension/src/entrypoints/popup/components/Forms/PasswordConfigForm.tsx
+++ b/apps/browser-extension/src/entrypoints/popup/components/Forms/PasswordConfigForm.tsx
@@ -1,9 +1,8 @@
+import { sliderToLength, lengthToSlider, SLIDER_MIN, SLIDER_MAX } from '@aliasvault/client/utilities/PasswordLengthSlider';
import { MIN_WORD_COUNT, MAX_WORD_COUNT, DEFAULT_WORD_COUNT, getLanguageInfo, resolveDefaultLanguage } from '@aliasvault/models/defaults';
import React from 'react';
import { useTranslation } from 'react-i18next';
-import { sliderToLength, lengthToSlider, SLIDER_MIN, SLIDER_MAX } from '@/utils/PasswordLengthSlider';
-
import type {
PasswordSettings,
PasswordGeneratorType,
diff --git a/apps/browser-extension/src/entrypoints/popup/components/Forms/PasswordField.tsx b/apps/browser-extension/src/entrypoints/popup/components/Forms/PasswordField.tsx
index bb21c5044..15f4a961b 100644
--- a/apps/browser-extension/src/entrypoints/popup/components/Forms/PasswordField.tsx
+++ b/apps/browser-extension/src/entrypoints/popup/components/Forms/PasswordField.tsx
@@ -1,4 +1,5 @@
import * as RustCore from '@aliasvault/client/rust/RustCore';
+import { sliderToLength, lengthToSlider, SLIDER_MIN, SLIDER_MAX } from '@aliasvault/client/utilities/PasswordLengthSlider';
import { MIN_WORD_COUNT, MAX_WORD_COUNT, DEFAULT_WORD_COUNT } from '@aliasvault/models/defaults';
import React, { useState, useEffect, useCallback } from 'react';
import { useTranslation } from 'react-i18next';
@@ -6,8 +7,6 @@ import { useTranslation } from 'react-i18next';
import PasswordConfigDialog from '@/entrypoints/popup/components/Dialogs/PasswordConfigDialog';
import { useDb } from '@/entrypoints/popup/context/DbContext';
-import { sliderToLength, lengthToSlider, SLIDER_MIN, SLIDER_MAX } from '@/utils/PasswordLengthSlider';
-
import type { PasswordSettings } from '@aliasvault/models/vault';
interface IPasswordFieldProps {
diff --git a/apps/browser-extension/src/entrypoints/popup/components/Items/Details/TotpEditor.tsx b/apps/browser-extension/src/entrypoints/popup/components/Items/Details/TotpEditor.tsx
index a20c96c87..dd060402f 100644
--- a/apps/browser-extension/src/entrypoints/popup/components/Items/Details/TotpEditor.tsx
+++ b/apps/browser-extension/src/entrypoints/popup/components/Items/Details/TotpEditor.tsx
@@ -1,6 +1,5 @@
-import { buildOtpAuthUri } from '@aliasvault/client/items/TotpUtility';
-import { normalizeTotpAlgorithm, normalizeTotpDigits, normalizeTotpPeriod, TOTP_DEFAULT_ALGORITHM, TOTP_DEFAULT_DIGITS, TOTP_DEFAULT_PERIOD } from '@aliasvault/models/vault';
-import * as OTPAuth from 'otpauth';
+import { buildOtpAuthUri, parseOtpAuthUri } from '@aliasvault/client/items/OtpAuthUri';
+import { TOTP_DEFAULT_ALGORITHM, TOTP_DEFAULT_DIGITS, TOTP_DEFAULT_PERIOD } from '@aliasvault/models/vault';
import QRCode from 'qrcode';
import React, { useState } from 'react';
import { useTranslation } from 'react-i18next';
@@ -69,22 +68,19 @@ const TotpEditor: React.FC<TotpEditorProps> = ({
// Check if it's a TOTP URI
if (secretKey.toLowerCase().startsWith('otpauth://totp/')) {
- try {
- const uri = OTPAuth.URI.parse(secretKey);
- if (uri instanceof OTPAuth.TOTP) {
- secretKey = uri.secret.base32;
- // Keep the URI's parameters instead of silently regenerating codes with the defaults.
- algorithm = normalizeTotpAlgorithm(uri.algorithm);
- digits = normalizeTotpDigits(uri.digits);
- period = normalizeTotpPeriod(uri.period);
- // If name is empty, use the label from the URI
- if (!name && uri.label) {
- name = uri.label;
- }
- }
- } catch {
+ const parsed = parseOtpAuthUri(secretKey);
+ if (!parsed) {
throw new Error(t('totp.errors.invalidSecretKey'));
}
+ secretKey = parsed.secret;
+ // Keep the URI's parameters instead of silently regenerating codes with the defaults.
+ algorithm = parsed.algorithm;
+ digits = parsed.digits;
+ period = parsed.period;
+ // If name is empty, use the account from the URI label
+ if (!name && parsed.account) {
+ name = parsed.account;
+ }
}
// Remove spaces from the secret key
diff --git a/apps/browser-extension/src/entrypoints/popup/pages/auth/Login.tsx b/apps/browser-extension/src/entrypoints/popup/pages/auth/Login.tsx
index c36ac48f4..f0e73ea61 100644
--- a/apps/browser-extension/src/entrypoints/popup/pages/auth/Login.tsx
+++ b/apps/browser-extension/src/entrypoints/popup/pages/auth/Login.tsx
@@ -4,6 +4,7 @@ import { ClientUpgradeRequiredError } from '@aliasvault/client/api/errors/Client
import { ServerUpdateRequiredError } from '@aliasvault/client/api/errors/ServerUpdateRequiredError';
import { VaultProcessingError } from '@aliasvault/client/api/errors/VaultProcessingError';
import { SrpAuthService } from '@aliasvault/client/auth/SrpAuthService';
+import { SrpLoginService } from '@aliasvault/client/auth/SrpLoginService';
import { VaultKeyService } from '@aliasvault/client/auth/VaultKeyService';
import { AppInfo } from '@aliasvault/client/platform/AppInfo';
import React, { useEffect, useState } from 'react';
@@ -22,7 +23,6 @@ import { useHeaderButtons } from '@/entrypoints/popup/context/HeaderButtonsConte
import { useLoading } from '@/entrypoints/popup/context/LoadingContext';
import { useWebApi } from '@/entrypoints/popup/context/WebApiContext';
import { PopoutUtility } from '@/entrypoints/popup/utils/PopoutUtility';
-import SrpUtility from '@/entrypoints/popup/utils/SrpUtility';
import { StorageKeys } from '@/utils/constants/storageKeys';
import { sendMessage } from '@/utils/messaging/ExtensionMessaging';
@@ -67,7 +67,7 @@ const Login: React.FC = () => {
const [vaultError, setVaultError] = useState<VaultProcessingError | null>(null);
const [showMobileLoginModal, setShowMobileLoginModal] = useState(false);
const webApi = useWebApi();
- const srpUtil = new SrpUtility(webApi);
+ const srpUtil = new SrpLoginService(webApi);
/**
* Pull the vault from the server.
diff --git a/apps/browser-extension/src/entrypoints/popup/pages/auth/Unlock.tsx b/apps/browser-extension/src/entrypoints/popup/pages/auth/Unlock.tsx
index bdac2e692..9d10c46ab 100644
--- a/apps/browser-extension/src/entrypoints/popup/pages/auth/Unlock.tsx
+++ b/apps/browser-extension/src/entrypoints/popup/pages/auth/Unlock.tsx
@@ -2,6 +2,7 @@ import { hasErrorCode, getErrorMessage, extractErrorCode, AppErrorCode } from '@
import { ClientUpgradeRequiredError } from '@aliasvault/client/api/errors/ClientUpgradeRequiredError';
import { VaultVersionIncompatibleError } from '@aliasvault/client/api/errors/VaultVersionIncompatibleError';
import { SrpAuthService } from '@aliasvault/client/auth/SrpAuthService';
+import { SrpLoginService } from '@aliasvault/client/auth/SrpLoginService';
import { VaultKeyService } from '@aliasvault/client/auth/VaultKeyService';
import React, { useEffect, useState, useCallback, useRef } from 'react';
import { useTranslation } from 'react-i18next';
@@ -22,7 +23,6 @@ import { useHeaderButtons } from '@/entrypoints/popup/context/HeaderButtonsConte
import { useLoading } from '@/entrypoints/popup/context/LoadingContext';
import { useWebApi } from '@/entrypoints/popup/context/WebApiContext';
import { PopoutUtility } from '@/entrypoints/popup/utils/PopoutUtility';
-import SrpUtility from '@/entrypoints/popup/utils/SrpUtility';
import { LocalPreferencesService } from '@/utils/LocalPreferencesService';
import { sendMessage } from '@/utils/messaging/ExtensionMessaging';
@@ -58,7 +58,7 @@ const Unlock: React.FC = () => {
const { setHeaderButtons } = useHeaderButtons();
const webApi = useWebApi();
- const srpUtil = new SrpUtility(webApi);
+ const srpUtil = new SrpLoginService(webApi);
// Unlock mode state
const [unlockMode, setUnlockMode] = useState<UnlockMode>('password');
diff --git a/apps/browser-extension/src/entrypoints/popup/utils/ConversionUtility.ts b/apps/browser-extension/src/entrypoints/popup/utils/ConversionUtility.ts
index b7840cfe4..810a2f0bb 100644
--- a/apps/browser-extension/src/entrypoints/popup/utils/ConversionUtility.ts
+++ b/apps/browser-extension/src/entrypoints/popup/utils/ConversionUtility.ts
@@ -127,15 +127,6 @@ class ConversionUtility {
return html;
}
}
-
- /**
- * Normalize a username by converting it to lowercase and trimming whitespace.
- * @param username The username to normalize.
- * @returns The normalized username.
- */
- public normalizeUsername(username: string): string {
- return username.toLowerCase().trim();
- }
}
export default new ConversionUtility();
diff --git a/apps/browser-extension/src/entrypoints/popup/utils/SrpUtility.ts b/apps/browser-extension/src/entrypoints/popup/utils/SrpUtility.ts
deleted file mode 100644
index 4bd8b2fe2..000000000
--- a/apps/browser-extension/src/entrypoints/popup/utils/SrpUtility.ts
+++ /dev/null
@@ -1,143 +0,0 @@
-import { ApiAuthError } from '@aliasvault/client/api/errors/ApiAuthError';
-import { WebApiService } from '@aliasvault/client/api/WebApiService';
-import { SrpAuthService } from '@aliasvault/client/auth/SrpAuthService';
-import { throwIfServerPredatesV2Api } from '@aliasvault/client/sync/LegacyStorageModelMigration';
-
-import type { LoginResponse, ValidateLoginResponse, ValidateLoginRequest, ValidateLoginRequest2Fa, BadRequestResponse } from '@aliasvault/models/webapi';
-
-/**
- * Utility class for SRP authentication operations.
- *
- * This class wraps the SrpAuthService to provide WebApiService-aware
- * authentication methods for the browser extension popup.
- */
-class SrpUtility {
- private readonly webApiService: WebApiService;
-
- /**
- * Constructor for the SrpUtility class.
- *
- * @param webApiService - The WebApiService instance.
- */
- public constructor(webApiService: WebApiService) {
- this.webApiService = webApiService;
- }
-
- /**
- * Reject a response that a server predating the v2 API produced.
- * TODO: can be deleted later once all users have migrated to the new storage format and we don't support v1 API anymore.
- * @param response - the raw auth response
- */
- private async assertServerSupportsV2Api(response: Response): Promise<void> {
- await throwIfServerPredatesV2Api(response.status, await this.webApiService.getApiUrl());
- }
-
- /**
- * Initiate login with server.
- */
- public async initiateLogin(username: string): Promise<LoginResponse> {
- const normalizedUsername = SrpAuthService.normalizeUsername(username);
-
- const response = await this.webApiService.rawFetch('Auth/login', {
- method: 'POST',
- headers: {
- 'Content-Type': 'application/json',
- },
- body: JSON.stringify({ username: normalizedUsername }),
- });
-
- await this.assertServerSupportsV2Api(response);
-
- // Check if response is a bad request (400)
- if (response.status === 400) {
- const badRequestResponse = await response.json() as BadRequestResponse;
- throw new ApiAuthError(badRequestResponse.title);
- }
-
- // For other responses, try to parse as LoginResponse
- const loginResponse = await response.json() as LoginResponse;
- return loginResponse;
- }
-
- /**
- * Validate login with server using locally generated ephemeral and session proof.
- */
- public async validateLogin(
- username: string,
- passwordHashString: string,
- rememberMe: boolean,
- loginResponse: LoginResponse
- ): Promise<ValidateLoginResponse> {
- const normalizedUsername = SrpAuthService.normalizeUsername(username);
- const proof = await SrpAuthService.deriveLoginProof(loginResponse, normalizedUsername, passwordHashString);
-
- const model: ValidateLoginRequest = {
- username: normalizedUsername,
- rememberMe: rememberMe,
- ...proof,
- };
-
- const response = await this.webApiService.rawFetch('Auth/validate', {
- method: 'POST',
- headers: {
- 'Content-Type': 'application/json',
- },
- body: JSON.stringify(model),
- });
-
- await this.assertServerSupportsV2Api(response);
-
- // Check if response is a bad request (400)
- if (response.status === 400) {
- const badRequestResponse = await response.json() as BadRequestResponse;
- throw new ApiAuthError(badRequestResponse.title);
- }
-
- // For other responses, try to parse as ValidateLoginResponse
- const validateLoginResponse = await response.json() as ValidateLoginResponse;
- return validateLoginResponse;
- }
-
- /**
- * Validate login with 2FA with server using locally generated ephemeral and session proof.
- */
- public async validateLogin2Fa(
- username: string,
- passwordHashString: string,
- rememberMe: boolean,
- loginResponse: LoginResponse,
- code2Fa: number
- ): Promise<ValidateLoginResponse> {
- const normalizedUsername = SrpAuthService.normalizeUsername(username);
- const proof = await SrpAuthService.deriveLoginProof(loginResponse, normalizedUsername, passwordHashString);
-
- const model: ValidateLoginRequest2Fa = {
- username: normalizedUsername,
- rememberMe,
- ...proof,
- code2Fa,
- };
-
- const response = await this.webApiService.rawFetch('Auth/validate-2fa', {
- method: 'POST',
- headers: {
- 'Content-Type': 'application/json',
- },
- body: JSON.stringify(model),
- });
-
- await this.assertServerSupportsV2Api(response);
-
- // Check if response is a bad request (400)
- if (response.status === 400) {
- const badRequestResponse = await response.json() as BadRequestResponse;
- throw new ApiAuthError(badRequestResponse.title);
- }
-
- // For other responses, try to parse as ValidateLoginResponse
- const validateLoginResponse = await response.json() as ValidateLoginResponse;
- return validateLoginResponse;
- }
-}
-
-export default SrpUtility;
diff --git a/apps/browser-extension/src/utils/PasswordLengthSlider.ts b/apps/browser-extension/src/utils/PasswordLengthSlider.ts
deleted file mode 100644
index cbdf7bf0b..000000000
--- a/apps/browser-extension/src/utils/PasswordLengthSlider.ts
+++ /dev/null
@@ -1,52 +0,0 @@
-/**
- * Utility functions for password length slider with non-linear scaling.
- *
- * The slider uses a power curve to provide fine-grained control at lower values
- * (where most users operate, e.g., 12-32 chars) and coarser control at higher values
- * (64-256 chars).
- *
- * This makes it easy to select common password lengths while still allowing
- * very long passwords when needed.
- */
-import { MIN_PASSWORD_LENGTH, MAX_PASSWORD_LENGTH } from '@aliasvault/models/defaults';
-
-/** Slider minimum value (internal representation) */
-export const SLIDER_MIN = 0;
-
-/** Slider maximum value (internal representation) */
-export const SLIDER_MAX = 100;
-
-/**
- * Exponent for the power curve.
- * Higher values = more precision at lower lengths.
- * 2.0 gives a good balance where ~50% slider = ~70 chars
- */
-const EXPONENT = 2.0;
-
-/**
- * Convert a slider position (0-100) to an actual password length (8-256).
- * Uses a power curve for non-linear scaling.
- *
- * @param sliderValue - The slider position (0-100)
- * @returns The password length (8-256)
- */
-export function sliderToLength(sliderValue: number): number {
- const normalized = Math.max(0, Math.min(1, sliderValue / SLIDER_MAX));
- const curved = Math.pow(normalized, EXPONENT);
- const length = MIN_PASSWORD_LENGTH + curved * (MAX_PASSWORD_LENGTH - MIN_PASSWORD_LENGTH);
- return Math.round(length);
-}
-
-/**
- * Convert a password length (8-256) to a slider position (0-100).
- * Inverse of sliderToLength.
- *
- * @param length - The password length (8-256)
- * @returns The slider position (0-100)
- */
-export function lengthToSlider(length: number): number {
- const clampedLength = Math.max(MIN_PASSWORD_LENGTH, Math.min(MAX_PASSWORD_LENGTH, length));
- const normalized = (clampedLength - MIN_PASSWORD_LENGTH) / (MAX_PASSWORD_LENGTH - MIN_PASSWORD_LENGTH);
- const curved = Math.pow(normalized, 1 / EXPONENT);
- return curved * SLIDER_MAX;
-}