Skip to content

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

Add shared MobileLoginService to core/client (#2413)

Leendert de Borst7c9d3b81000d
diff --git a/apps/browser-extension/src/entrypoints/popup/components/Dialogs/MobileUnlockModal.tsx b/apps/browser-extension/src/entrypoints/popup/components/Dialogs/MobileUnlockModal.tsx
index 5f5c42527..bfd826760 100644
--- a/apps/browser-extension/src/entrypoints/popup/components/Dialogs/MobileUnlockModal.tsx
+++ b/apps/browser-extension/src/entrypoints/popup/components/Dialogs/MobileUnlockModal.tsx
@@ -1,14 +1,12 @@
+import { isMobileLoginErrorCode, MOBILE_LOGIN_REQUEST_LIFETIME_SECONDS, MobileLoginErrorCode, MobileLoginService } from '@aliasvault/client/auth/MobileLoginService';
import QRCode from 'qrcode';
import React, { useEffect, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
import ModalWrapper from '@/entrypoints/popup/components/Dialogs/ModalWrapper';
-import { MobileLoginErrorCode } from '@/entrypoints/popup/types/MobileLoginErrorCode';
-import { MobileLoginUtility } from '@/entrypoints/popup/utils/MobileLoginUtility';
-
-import type { MobileLoginResult } from '@/utils/types/messaging/MobileLoginResult';
import type { WebApiService } from '@aliasvault/client/api/WebApiService';
+import type { MobileLoginResult } from '@aliasvault/client/auth/MobileLoginService';
interface IMobileUnlockModalProps {
isOpen: boolean;
@@ -32,8 +30,8 @@ const MobileUnlockModal: React.FC<IMobileUnlockModalProps> = ({
const [qrCodeUrl, setQrCodeUrl] = useState<string | null>(null);
const [verificationCode, setVerificationCode] = useState<string | null>(null);
const [error, setError] = useState<MobileLoginErrorCode | null>(null);
- const [timeRemaining, setTimeRemaining] = useState<number>(120); // 2 minutes in seconds
- const mobileLoginRef = useRef<MobileLoginUtility | null>(null);
+ const [timeRemaining, setTimeRemaining] = useState<number>(MOBILE_LOGIN_REQUEST_LIFETIME_SECONDS)
+ const mobileLoginRef = useRef<MobileLoginService | null>(null);
const countdownIntervalRef = useRef<NodeJS.Timeout | null>(null);
/**
@@ -45,8 +43,6 @@ const MobileUnlockModal: React.FC<IMobileUnlockModalProps> = ({
return t('common.errors.mobileLoginRequestExpired');
case MobileLoginErrorCode.DECLINED:
return t('common.errors.mobileLoginRequestDeclined');
- case MobileLoginErrorCode.SERVER_OUTDATED:
- return t('common.errors.serverVersionNotSupported');
case MobileLoginErrorCode.GENERIC:
default:
return t('common.errors.unknownError');
@@ -90,11 +86,11 @@ const MobileUnlockModal: React.FC<IMobileUnlockModalProps> = ({
setError(null);
setQrCodeUrl(null);
setVerificationCode(null);
- setTimeRemaining(120);
+ setTimeRemaining(MOBILE_LOGIN_REQUEST_LIFETIME_SECONDS);
// Initialize mobile login utility
if (!mobileLoginRef.current) {
- mobileLoginRef.current = new MobileLoginUtility(webApi);
+ mobileLoginRef.current = new MobileLoginService(webApi);
}
// Initiate mobile login and get the QR code text plus the number the user taps in the mobile app
@@ -108,7 +104,7 @@ const MobileUnlockModal: React.FC<IMobileUnlockModalProps> = ({
setVerificationCode(code);
// Start polling for response
- await mobileLoginRef.current.startPolling(
+ mobileLoginRef.current.startPolling(
async (result: MobileLoginResult) => {
try {
// Call success callback (parent handles loading state)
@@ -129,11 +125,7 @@ const MobileUnlockModal: React.FC<IMobileUnlockModalProps> = ({
);
} catch (err) {
// err is a MobileLoginErrorCode thrown by initiate()
- if (typeof err === 'string' && Object.values(MobileLoginErrorCode).includes(err as MobileLoginErrorCode)) {
- setError(err as MobileLoginErrorCode);
- } else {
- setError(MobileLoginErrorCode.GENERIC);
- }
+ setError(isMobileLoginErrorCode(err) ? err : MobileLoginErrorCode.GENERIC);
}
};
@@ -163,7 +155,7 @@ const MobileUnlockModal: React.FC<IMobileUnlockModalProps> = ({
}
setQrCodeUrl(null);
setError(null);
- setTimeRemaining(120);
+ setTimeRemaining(MOBILE_LOGIN_REQUEST_LIFETIME_SECONDS);
onClose();
};
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 e88371474..61fcc431a 100644
--- a/apps/browser-extension/src/entrypoints/popup/pages/auth/Login.tsx
+++ b/apps/browser-extension/src/entrypoints/popup/pages/auth/Login.tsx
@@ -29,10 +29,10 @@ import { apiErrorMessage } from '@/utils/ApiErrors';
import { StorageKeys } from '@/utils/constants/storageKeys';
import { logFailure } from '@/utils/Diagnostics';
import { sendMessage } from '@/utils/messaging/ExtensionMessaging';
-import type { MobileLoginResult } from '@/utils/types/messaging/MobileLoginResult';
import { vaultStateEvents } from '@/events/VaultStateEvents';
+import type { MobileLoginResult } from '@aliasvault/client/auth/MobileLoginService';
import type { UnlockKeyDerivationParams } from '@aliasvault/models/metadata';
import type { LoginResponse } from '@aliasvault/models/webapi';
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 d6479eaef..c053755f2 100644
--- a/apps/browser-extension/src/entrypoints/popup/pages/auth/Unlock.tsx
+++ b/apps/browser-extension/src/entrypoints/popup/pages/auth/Unlock.tsx
@@ -36,10 +36,11 @@ import {
resetFailedAttempts,
unlockWithPin
} from '@/utils/PinUnlockService';
-import type { MobileLoginResult } from '@/utils/types/messaging/MobileLoginResult';
import { vaultStateEvents } from '@/events/VaultStateEvents';
+import type { MobileLoginResult } from '@aliasvault/client/auth/MobileLoginService';
+
/**
* Concrete unlock screens the page can render. Mobile-app unlock is shown
* as a modal on top of one of these screens, not as its own mode.
diff --git a/apps/browser-extension/src/entrypoints/popup/types/MobileLoginErrorCode.ts b/apps/browser-extension/src/entrypoints/popup/types/MobileLoginErrorCode.ts
deleted file mode 100644
index 66eca90b9..000000000
--- a/apps/browser-extension/src/entrypoints/popup/types/MobileLoginErrorCode.ts
+++ /dev/null
@@ -1,25 +0,0 @@
-/**
- * Error codes for mobile login operations.
- * These codes are used to provide translatable error messages to users.
- */
-export enum MobileLoginErrorCode {
- /**
- * The mobile login request has timed out after 2 minutes.
- */
- TIMEOUT = 'TIMEOUT',
-
- /**
- * The server is outdated and does not support mobile login.
- */
- SERVER_OUTDATED = 'SERVER_OUTDATED',
-
- /**
- * The request was declined on the mobile device.
- */
- DECLINED = 'DECLINED',
-
- /**
- * A generic error occurred during mobile login.
- */
- GENERIC = 'GENERIC',
-}
diff --git a/apps/browser-extension/src/i18n/locales/en.json b/apps/browser-extension/src/i18n/locales/en.json
index ca79b281c..ff9ef6f15 100644
--- a/apps/browser-extension/src/i18n/locales/en.json
+++ b/apps/browser-extension/src/i18n/locales/en.json
@@ -112,7 +112,6 @@
"clientVersionNotSupported": "This version of the AliasVault browser extension is not supported by the server anymore. Please update your browser extension to the latest version.",
"browserExtensionOutdated": "This browser extension is outdated and cannot be used to access this vault. Please update this browser extension to continue.",
"serverVersionNotSupported": "The AliasVault server needs to be updated to a newer version in order to use this browser extension. Please contact support if you need help.",
- "serverVersionTooOld": "The AliasVault server needs to be updated to a newer version in order to use this feature. Please contact the server admin if you need help.",
"unknownError": "An unknown error occurred",
"unknownErrorTryAgain": "An unknown error occurred. Please try again.",
"vaultNotAvailable": "Vault not available",
@@ -130,7 +129,10 @@
"wrongPassword": "Incorrect password. Please try again.",
"sessionExpired": "Your session has expired. Please log in again.",
"mobileLoginRequestExpired": "Mobile login request timed out. Please reload the page and try again.",
- "mobileLoginRequestDeclined": "The login request was declined on your mobile device."
+ "mobileLoginRequestDeclined": "The login request was declined on your mobile device.",
+ "keyChainUnreadable": "Your password is correct, but the encryption keys of your vault could not be opened. Please contact support.",
+ "unexpectedErrorContactSupport": "An unexpected error occurred. Please try again, and contact support if the problem persists.",
+ "vaultDataUnreadable": "Your vault data could not be read, so your data is not accessible at this moment. Please contact support."
},
"apiErrors": {
"UNKNOWN_ERROR": "An unknown error occurred. Please try again.",
diff --git a/apps/browser-extension/src/utils/types/messaging/MobileLoginResult.ts b/apps/browser-extension/src/utils/types/messaging/MobileLoginResult.ts
deleted file mode 100644
index 07ff53ff5..000000000
--- a/apps/browser-extension/src/utils/types/messaging/MobileLoginResult.ts
+++ /dev/null
@@ -1,39 +0,0 @@
-/**
- * Result of a successful mobile login containing decrypted authentication data.
- */
-export type MobileLoginResult = {
- /**
- * The username.
- */
- username: string;
-
- /**
- * The JWT access token.
- */
- token: string;
-
- /**
- * The refresh token.
- */
- refreshToken: string;
-
- /**
- * The account unlock key the mobile app sent.
- */
- unlockKey: string;
-
- /**
- * The user's salt for key derivation.
- */
- salt: string;
-
- /**
- * The encryption type (e.g., "Argon2id").
- */
- encryptionType: string;
-
- /**
- * The encryption settings JSON string.
- */
- encryptionSettings: string;
-}
diff --git a/apps/browser-extension/src/entrypoints/popup/utils/MobileLoginUtility.ts b/core/client/src/auth/MobileLoginService.ts
similarity index 52%
rename from apps/browser-extension/src/entrypoints/popup/utils/MobileLoginUtility.ts
rename to core/client/src/auth/MobileLoginService.ts
index 93ba43d51..ae516a4e9 100644
--- a/apps/browser-extension/src/entrypoints/popup/utils/MobileLoginUtility.ts
+++ b/core/client/src/auth/MobileLoginService.ts
@@ -1,74 +1,91 @@
-import { Buffer } from 'buffer';
+import EncryptionUtility from '../crypto/EncryptionUtility';
+import { bytesToBase64 } from '../utilities/Base64';
-import { MobileLoginProtocol } from '@aliasvault/client/auth/MobileLoginProtocol';
-import EncryptionUtility from '@aliasvault/client/crypto/EncryptionUtility';
-import { serverPredatesV2Api } from '@aliasvault/client/sync/LegacyStorageModelMigration';
+import { MobileLoginProtocol } from './MobileLoginProtocol';
-import { MobileLoginErrorCode } from '@/entrypoints/popup/types/MobileLoginErrorCode';
+import type { WebApiService } from '../api/WebApiService';
+import type { MobileLoginInitiateResponse, MobileLoginPayload, MobileLoginPollResponse } from '@aliasvault/models/webapi';
-import type { MobileLoginResult } from '@/utils/types/messaging/MobileLoginResult';
+/**
+ * Error codes for mobile login failures.
+ */
+export enum MobileLoginErrorCode {
+ TIMEOUT = 'TIMEOUT',
+ DECLINED = 'DECLINED',
+ GENERIC = 'GENERIC',
+}
-import type { WebApiService } from '@aliasvault/client/api/WebApiService';
-import type { MobileLoginInitiateResponse, MobileLoginPayload, MobileLoginPollResponse } from '@aliasvault/models/webapi';
+/**
+ * Whether a thrown value is a mobile login error code.
+ */
+export function isMobileLoginErrorCode(value: unknown): value is MobileLoginErrorCode {
+ return typeof value === 'string' && Object.values(MobileLoginErrorCode).includes(value as MobileLoginErrorCode);
+}
+
+/**
+ * The decrypted session and unlock key of an approved mobile login.
+ */
+export type MobileLoginResult = {
+ username: string;
+ token: string;
+ refreshToken: string;
+ unlockKey: string;
+ salt: string;
+ encryptionType: string;
+ encryptionSettings: string;
+}
/**
- * Utility class for mobile login operations
+ * The part of the API client the mobile login requests need.
*/
-export class MobileLoginUtility {
- private webApi: WebApiService;
- private pollingInterval: NodeJS.Timeout | null = null;
- private pollingTimeout: NodeJS.Timeout | null = null;
+export type MobileLoginApi = Pick<WebApiService, 'rawFetch'>;
+
+/** Seconds a mobile login request stays valid in the UI (server holds it active for a few seconds longer for delayed confirms). */
+export const MOBILE_LOGIN_REQUEST_LIFETIME_SECONDS = 120;
+
+const POLL_INTERVAL_MS = 3000;
+const POLL_TIMEOUT_MS = 210000; // 3.5 minutes
+
+/**
+ * The client side of a mobile login (QR unlock): creates the request, then polls until the mobile app approves or declines it.
+ */
+export class MobileLoginService {
+ private pollingInterval: ReturnType<typeof setInterval> | null = null;
+ private pollingTimeout: ReturnType<typeof setTimeout> | null = null;
private isPollInFlight = false;
private requestId: string | null = null;
private pollSecret: string | null = null;
private privateKey: CryptoKey | null = null;
/**
- * Constructor for the MobileLoginUtility class.
- *
- * @param {WebApiService} webApi - The WebApiService instance.
+ * Create the service.
+ * @param api - The API client the requests go through
*/
- public constructor(webApi: WebApiService) {
- this.webApi = webApi;
- }
+ public constructor(private readonly api: MobileLoginApi) {}
/**
- * Initiates a mobile login request.
- * @returns The text for the QR code and the verification code the user has to type into the mobile app
- * @throws {MobileLoginErrorCode} If initiation fails
+ * Create a mobile login request.
+ * @returns The text for the QR code and the verification code the user has to pick in the mobile app
+ * @throws {MobileLoginErrorCode} If the request could not be created
*/
public async initiate(): Promise<{ qrPayload: string; verificationCode: string }> {
try {
const { publicKeyJwk, privateKey } = await EncryptionUtility.generateRsaKeyPairNonExtractable();
this.privateKey = privateKey;
- // Send public key to server (no auth required)
- const response = await this.webApi.rawFetch('auth/mobile-login/initiate', {
+ const response = await this.api.rawFetch('auth/mobile-login/initiate', {
method: 'POST',
- headers: {
- 'Content-Type': 'application/json',
- },
- body: JSON.stringify({
- clientPublicKey: publicKeyJwk,
- }),
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ clientPublicKey: publicKeyJwk }),
});
- /*
- * A 404 on this initiating call means the v2 API is missing altogether. Only this call may read a 404 that
- * way: the poll below answers 404 for an expired request, which is a normal outcome.
- */
- if (response.status === 404 && await serverPredatesV2Api(this.webApi)) {
- throw MobileLoginErrorCode.SERVER_OUTDATED;
- }
-
if (!response.ok) {
throw MobileLoginErrorCode.GENERIC;
}
const data = await response.json() as MobileLoginInitiateResponse;
if (!data.requestId || !data.pollSecret) {
- // A server without the poll secret still runs the old handshake, which this client no longer takes part in.
- throw MobileLoginErrorCode.SERVER_OUTDATED;
+ throw MobileLoginErrorCode.GENERIC;
}
this.requestId = data.requestId;
this.pollSecret = data.pollSecret;
@@ -78,27 +95,21 @@ export class MobileLoginUtility {
qrPayload: MobileLoginProtocol.buildQrPayload(data.requestId, await MobileLoginProtocol.computePublicKeyHash(publicKeyJwk)),
verificationCode: await MobileLoginProtocol.computeVerificationCode(publicKeyJwk),
};
- } catch (error) {
- if (typeof error === 'string' && Object.values(MobileLoginErrorCode).includes(error as MobileLoginErrorCode)) {
- throw error;
- }
+ } catch {
throw MobileLoginErrorCode.GENERIC;
}
}
/**
- * Starts polling the server for mobile login response
+ * Poll the server until the request is approved, declined or expired. Exactly one of the callbacks is called.
*/
- public async startPolling(
- onSuccess: (result: MobileLoginResult) => void,
- onError: (errorCode: MobileLoginErrorCode) => void
- ): Promise<void> {
+ public startPolling(onSuccess: (result: MobileLoginResult) => void, onError: (errorCode: MobileLoginErrorCode) => void): void {
if (!this.requestId || !this.pollSecret || !this.privateKey) {
throw new Error('Must call initiate() before starting polling');
}
/**
- * Polls the server for mobile login response
+ * One poll round.
*/
const pollFn = async (): Promise<void> => {
// An approved request can be collected once, so a slow poll must never overlap with the next one.
@@ -113,20 +124,15 @@ export class MobileLoginUtility {
return;
}
- const response = await this.webApi.rawFetch('auth/mobile-login/poll', {
+ const response = await this.api.rawFetch('auth/mobile-login/poll', {
method: 'POST',
- headers: {
- 'Content-Type': 'application/json',
- },
- body: JSON.stringify({
- requestId: this.requestId,
- pollSecret: this.pollSecret,
- }),
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ requestId: this.requestId, pollSecret: this.pollSecret }),
});
if (!response.ok) {
if (response.status === 404) {
- // Request expired or not found
+ // Request expired or not found.
this.cleanup();
onError(MobileLoginErrorCode.TIMEOUT);
return;
@@ -143,24 +149,22 @@ export class MobileLoginUtility {
}
if (data.status === 'Approved' && data.encryptedSymmetricKey && data.encryptedPayload && data.encryptedUnlockKey) {
- // Capture key locally; cleanup() nulls the field.
+ // Capture the key locally.
const privateKey = this.privateKey!;
this.cleanup();
- // The mobile app encrypted the unlock key with our public key
- const unlockKeyBytes = await EncryptionUtility.decryptWithPrivateKeyObject(data.encryptedUnlockKey, privateKey);
- const unlockKey = Buffer.from(unlockKeyBytes).toString('base64');
+ // The mobile app encrypted the unlock 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
- const symmetricKeyBytes = await EncryptionUtility.decryptWithPrivateKeyObject(data.encryptedSymmetricKey, privateKey);
- const symmetricKey = Buffer.from(symmetricKeyBytes).toString('base64');
+ // The server encrypted the session payload with a symmetric key, which is encrypted with our public key.
+ const symmetricKey = bytesToBase64(await EncryptionUtility.decryptWithPrivateKeyObject(data.encryptedSymmetricKey, privateKey));
const payload = JSON.parse(await EncryptionUtility.symmetricDecrypt(data.encryptedPayload, symmetricKey)) as MobileLoginPayload;
onSuccess({
username: payload.username,
token: payload.token,
refreshToken: payload.refreshToken,
- unlockKey: unlockKey,
+ unlockKey,
salt: payload.salt,
encryptionType: payload.encryptionType,
encryptionSettings: payload.encryptionSettings,
@@ -174,20 +178,17 @@ export class MobileLoginUtility {
}
};
- // Poll every 3 seconds
- this.pollingInterval = setInterval(pollFn, 3000);
-
- // Stop polling after 3.5 minutes (adds 1.5 minute buffer to default 2 minute timer for edge cases)
+ this.pollingInterval = setInterval(pollFn, POLL_INTERVAL_MS);
this.pollingTimeout = setTimeout(() => {
if (this.pollingInterval) {
this.cleanup();
onError(MobileLoginErrorCode.TIMEOUT);
}
- }, 210000);
+ }, POLL_TIMEOUT_MS);
}
/**
- * Stops polling the server and drops the private key reference.
+ * Stop polling and drop the private key reference.
*/
public stopPolling(): void {
if (this.pollingInterval) {
@@ -202,7 +203,7 @@ export class MobileLoginUtility {
}
/**
- * Cleans up resources
+ * Stop polling and forget the request.
*/
public cleanup(): void {
this.stopPolling();