Skip to content

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

Refactor register and login calls (#2159)

Leendert de Borst9b8ec85db754
diff --git a/apps/browser-extension/tests/helpers/test-api.ts b/apps/browser-extension/tests/helpers/test-api.ts
index 1a90c33d7..f5ecf52e6 100644
--- a/apps/browser-extension/tests/helpers/test-api.ts
+++ b/apps/browser-extension/tests/helpers/test-api.ts
@@ -5,7 +5,7 @@
*/
import { WebApiService } from '@aliasvault/client/api/WebApiService';
-import { SrpAuthService } from '@aliasvault/client/auth/SrpAuthService';
+import { SrpLoginService } from '@aliasvault/client/auth/SrpLoginService';
import { base64ToBytes } from '@aliasvault/client/utilities/Base64';
import * as OTPAuth from 'otpauth';
@@ -63,20 +63,13 @@ export async function registerTestUser(
username: string,
password: string
): Promise<{ tokenModel: TokenModel; encryptionKey: Uint8Array }> {
- const prepared = await SrpAuthService.prepareRegistration(username, password);
- const response = await fetch(`${WebApiService.versionedBaseUrl(apiBaseUrl)}Auth/register`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify(prepared.request),
- });
- if (!response.ok) {
- throw new Error(`Registration failed with status ${response.status}: ${await response.text()}`);
- }
+ const baseUrl = WebApiService.versionedBaseUrl(apiBaseUrl);
+ const auth = new SrpLoginService({ rawFetch: (endpoint, options) => fetch(`${baseUrl}${endpoint}`, options) });
+ const { token, keys, derivedKey } = await auth.register(username, password);
- const tokenModel = await response.json() as TokenModel;
- await pushInitialVault(apiBaseUrl, tokenModel.token, username, base64ToBytes(prepared.keys.vaultEncryptionKey));
+ await pushInitialVault(apiBaseUrl, token.token, username, base64ToBytes(keys.vaultEncryptionKey));
- return { tokenModel, encryptionKey: base64ToBytes(prepared.derivedKey) };
+ return { tokenModel: token, encryptionKey: base64ToBytes(derivedKey) };
}
/**
diff --git a/core/client/src/auth/MasterPasswordService.ts b/core/client/src/auth/MasterPasswordService.ts
index a0b7c9440..a16e55cc6 100644
--- a/core/client/src/auth/MasterPasswordService.ts
+++ b/core/client/src/auth/MasterPasswordService.ts
@@ -1,9 +1,7 @@
-import { AppErrorCode, extractErrorCode } from '../api/errors/AppErrorCodes';
import { StorageKeys } from '../constants/StorageKeys';
import { EncryptionUtility } from '../crypto/EncryptionUtility';
import { getPlatform } from '../platform/ClientPlatform';
import { VaultSyncHoldReason, withVaultSyncHold } from '../sync/VaultSyncHold';
-import { logDefect } from '../utilities/Diagnostics';
import { SrpAuthService, type SrpClientProof } from './SrpAuthService';
import { VaultKeyService } from './VaultKeyService';
@@ -36,15 +34,6 @@ export class PasswordChangedElsewhereError extends Error {
}
}
-/**
- * Outcome of a local master password check.
- */
-export enum PasswordVerificationResult {
- Success = 'Success',
- InvalidPassword = 'InvalidPassword',
- VerificationError = 'VerificationError',
-}
-
/** The SRP challenge a server endpoint issues before it accepts a password-confirmed action. */
export type SrpChallenge = {
salt: string;
@@ -71,36 +60,6 @@ export class MasterPasswordService {
return getPlatform().storage.get<UnlockKeyDerivationParams>(StorageKeys.UNLOCK_KEY_DERIVATION_PARAMS);
}
- /**
- * Verify the master password locally.
- * @param password - the master password to check
- */
- public static async verifyPassword(password: string): Promise<PasswordVerificationResult> {
- try {
- const parameters = await MasterPasswordService.getStoredDerivationParams();
- if (!parameters) {
- return PasswordVerificationResult.VerificationError;
- }
-
- // Without a cached chain a derived key cannot be checked against anything.
- if (!await VaultKeyService.hasLocalVaultKey()) {
- return PasswordVerificationResult.VerificationError;
- }
-
- const prepared = await SrpAuthService.prepareCredentials(password, parameters.salt, parameters.encryptionSettings);
- try {
- await VaultKeyService.verifyUnlockKey(prepared.passwordHashBase64);
- return PasswordVerificationResult.Success;
- } catch (error) {
- const code = error instanceof Error ? extractErrorCode(error.message) : null;
- return code === AppErrorCode.UNLOCK_KEY_REJECTED ? PasswordVerificationResult.InvalidPassword : PasswordVerificationResult.VerificationError;
- }
- } catch (error) {
- logDefect('[MasterPassword] Password verification failed unexpectedly', error);
- return PasswordVerificationResult.VerificationError;
- }
- }
-
/**
* 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.
diff --git a/core/client/src/auth/SrpAuthService.ts b/core/client/src/auth/SrpAuthService.ts
index 4a75a69ba..9d200e4ee 100644
--- a/core/client/src/auth/SrpAuthService.ts
+++ b/core/client/src/auth/SrpAuthService.ts
@@ -1,11 +1,10 @@
-import { WebApiService } from '../api/WebApiService';
import { createAccountKeyHierarchy, type AccountKeyBlobs, type AccountKeyHierarchy } from '../crypto/AccountKeys';
import { EncryptionUtility } from '../crypto/EncryptionUtility';
import { rustCore } from '../rust/RustCore';
import { bytesToBase64 } from '../utilities/Base64';
import type { SrpEphemeral, SrpSession } from '../rust/RustCoreTypes';
-import type { TokenModel, LoginResponse, BadRequestResponse } from '@aliasvault/models/webapi';
+import type { LoginResponse } from '@aliasvault/models/webapi';
/**
* Register request type for creating a new user.
@@ -28,19 +27,6 @@ export type PreparedRegistration = {
derivedKey: string;
};
-/**
- * Registration result type.
- */
-export type RegistrationResult = {
- success: boolean;
- token?: TokenModel;
- encryptionKey?: string;
- derivedKey?: string;
- accountKeys?: AccountKeyBlobs;
- accountPrivateKey?: string;
- error?: string;
-};
-
/**
* SRP client proof type.
*/
@@ -314,63 +300,6 @@ export class SrpAuthService {
derivedKey: material.kekBase64,
};
}
-
- /**
- * Registers a new user via the API.
- *
- * @param apiBaseUrl - The base URL of the API (e.g., 'http://localhost:5100')
- * @param username - The username for the new account
- * @param password - The password for the new account
- * @returns Registration result with token on success
- */
- public static async registerUser(
- apiBaseUrl: string,
- username: string,
- password: string
- ): Promise<RegistrationResult> {
- try {
- // Prepare registration data
- const prepared = await SrpAuthService.prepareRegistration(username, password);
-
- const baseUrl = WebApiService.versionedBaseUrl(apiBaseUrl);
-
- // Send registration request to API
- const response = await fetch(`${baseUrl}Auth/register`, {
- method: 'POST',
- headers: {
- 'Content-Type': 'application/json',
- },
- body: JSON.stringify(prepared.request),
- });
-
- if (!response.ok) {
- const errorText = await response.text();
- let errorMessage = `Registration failed with status ${response.status}`;
- try {
- const errorJson = JSON.parse(errorText) as BadRequestResponse;
- errorMessage = errorJson.title || errorMessage;
- } catch {
- errorMessage = errorText || errorMessage;
- }
- return { success: false, error: errorMessage };
- }
-
- const tokenModel = (await response.json()) as TokenModel;
- return {
- success: true,
- token: tokenModel,
- encryptionKey: prepared.keys.vaultEncryptionKey,
- derivedKey: prepared.derivedKey,
- accountKeys: prepared.keys.accountKeys,
- accountPrivateKey: prepared.keys.accountPrivateKey,
- };
- } catch (error) {
- return {
- success: false,
- error: error instanceof Error ? error.message : 'Unknown error occurred',
- };
- }
- }
}
export default SrpAuthService;
diff --git a/core/client/src/auth/SrpLoginService.ts b/core/client/src/auth/SrpLoginService.ts
index 699696f6c..caba85c63 100644
--- a/core/client/src/auth/SrpLoginService.ts
+++ b/core/client/src/auth/SrpLoginService.ts
@@ -4,22 +4,25 @@ import { throwIfServerPredatesV2Api } from '../sync/LegacyStorageModelMigration'
import { SrpAuthService } from './SrpAuthService';
import type { WebApiService } from '../api/WebApiService';
-import type { BadRequestResponse, LoginResponse, ValidateLoginRequest, ValidateLoginRequest2Fa, ValidateLoginResponse } from '@aliasvault/models/webapi';
+import type { AccountKeyHierarchy } from '../crypto/AccountKeys';
+import type { BadRequestResponse, LoginResponse, TokenModel, ValidateLoginRequest, ValidateLoginRequest2Fa, ValidateLoginResponse } from '@aliasvault/models/webapi';
/**
- * The part of an API client the login requests need.
+ * The part of an API client the auth requests need.
*/
export type SrpLoginApi = Pick<WebApiService, 'rawFetch'>;
/**
- * The recovery code variant of the validate request.
+ * A registered account: its session tokens plus the key material the caller keeps client-side.
*/
-type ValidateLoginRequestRecoveryCode = ValidateLoginRequest & {
- recoveryCode: string;
+export type RegistrationResult = {
+ token: TokenModel;
+ keys: AccountKeyHierarchy;
+ derivedKey: string;
};
/**
- * The SRP login requests: initiate, then validate with a password proof plus optionally a 2FA or recovery code.
+ * The SRP auth requests for registering and logging in.
*/
export class SrpLoginService {
/**
@@ -28,6 +31,19 @@ export class SrpLoginService {
*/
public constructor(private readonly api: SrpLoginApi) {}
+ /**
+ * Register a new account with its SRP verifier and account key hierarchy, both created client-side.
+ * @param username - The username
+ * @param password - The master password
+ * @returns The session tokens and key material of the new account
+ * @throws {ApiAuthError} when the server refuses the registration
+ */
+ public async register(username: string, password: string): Promise<RegistrationResult> {
+ const prepared = await SrpAuthService.prepareRegistration(username, password);
+ const token = await this.parseAuthResponse<TokenModel>(await this.post('Auth/register', prepared.request));
+ return { token, keys: prepared.keys, derivedKey: prepared.derivedKey };
+ }
+
/**
* Initiate login with the server.
* @param username - The username
@@ -69,22 +85,6 @@ export class SrpLoginService {
return this.parseAuthResponse<ValidateLoginResponse>(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 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> {
- const normalizedUsername = SrpAuthService.normalizeUsername(username);
- const proof = await SrpAuthService.deriveLoginProof(loginResponse, normalizedUsername, passwordHashString);
- const model: ValidateLoginRequestRecoveryCode = { username: normalizedUsername, rememberMe, ...proof, recoveryCode };
- return this.parseAuthResponse<ValidateLoginResponse>(await this.post('Auth/validate-recovery-code', model));
- }
-
/**
* Parse an auth response, turning a 400 into an ApiAuthError carrying the server's error code.
* @param response - The raw response