Skip to content

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

Implement 2FA for login flow (#541)

Leendert de Borstc28f6f05b28d
diff --git a/browser-extensions/chrome/src/app/pages/Login.tsx b/browser-extensions/chrome/src/app/pages/Login.tsx
index 2380f2f6f..afb2a3d87 100644
--- a/browser-extensions/chrome/src/app/pages/Login.tsx
+++ b/browser-extensions/chrome/src/app/pages/Login.tsx
@@ -6,8 +6,9 @@ import { Buffer } from 'buffer';
import Button from '../components/Button';
import EncryptionUtility from '../../shared/EncryptionUtility';
import SrpUtility from '../utils/SrpUtility';
-import { VaultResponse } from '../../shared/types/webapi/VaultResponse';
import { useLoading } from '../context/LoadingContext';
+import { VaultResponse } from '../../shared/types/webapi/VaultResponse';
+import { LoginResponse } from '../../shared/types/webapi/Login';
/**
* Login page
@@ -21,6 +22,11 @@ const Login: React.FC = () => {
});
const { showLoading, hideLoading } = useLoading();
const [rememberMe, setRememberMe] = useState(true);
+ const [loginResponse, setLoginResponse] = useState<LoginResponse | null>(null);
+ const [passwordHashString, setPasswordHashString] = useState<string | null>(null);
+ const [passwordHashBase64, setPasswordHashBase64] = useState<string | null>(null);
+ const [twoFactorRequired, setTwoFactorRequired] = useState(false);
+ const [twoFactorCode, setTwoFactorCode] = useState('');
const [error, setError] = useState<string | null>(null);
const webApi = useWebApi();
const srpUtil = new SrpUtility(webApi);
@@ -45,9 +51,13 @@ const Login: React.FC = () => {
loginResponse.encryptionType,
loginResponse.encryptionSettings
);
+
// Convert uint8 array to uppercase hex string which is expected by the server.
const passwordHashString = Buffer.from(passwordHash).toString('hex').toUpperCase();
+ // Get the derived key as base64 string required for decryption.
+ const passwordHashBase64 = Buffer.from(passwordHash).toString('base64');
+
// 2. Validate login with SRP protocol
const validationResponse = await srpUtil.validateLogin(
credentials.username,
@@ -56,6 +66,22 @@ const Login: React.FC = () => {
loginResponse
);
+ // 3. Handle 2FA if required
+ if (validationResponse.requiresTwoFactor) {
+ // Store login response as we need it for 2FA validation
+ setLoginResponse(loginResponse);
+ // Store password hash string as we need it for 2FA validation
+ setPasswordHashString(passwordHashString);
+ // Store password hash base64 as we need it for decryption
+ setPasswordHashBase64(passwordHashBase64);
+ setTwoFactorRequired(true);
+ // Show app.
+ hideLoading();
+ return;
+ }
+
+ // 4. TODO: handle recovery code if required (or link to main client instead)
+
// Store access and refresh token using the context
if (validationResponse.token) {
// Store auth info
@@ -67,16 +93,9 @@ const Login: React.FC = () => {
// Make another API call trying to get latest vault
const vaultResponseJson = await webApi.get('Vault') as VaultResponse;
- // Get the derived key as base64 string required for decryption.
- const passwordHashBase64 = Buffer.from(passwordHash).toString('base64');
-
// Initialize the SQLite context with the new vault data.
await dbContext.initializeDatabase(vaultResponseJson, passwordHashBase64);
- // 3. TODO: Handle 2FA if required
-
- // 4. TODO: handle recovery code if required (or link to main client instead)
-
// Show app.
hideLoading();
} catch (err) {
@@ -86,6 +105,57 @@ const Login: React.FC = () => {
}
};
+ /**
+ * Handle two factor submit.
+ */
+ const handleTwoFactorSubmit = async (e: React.FormEvent) : Promise<void> => {
+ e.preventDefault();
+ setError(null);
+
+ if (!passwordHashString || !passwordHashBase64) {
+ throw new Error('Password hash not found');
+ }
+
+ try {
+ showLoading();
+
+ // TODO: Implement 2FA validation API call
+ const validationResponse = await srpUtil.validateLogin2Fa(
+ credentials.username,
+ passwordHashString,
+ rememberMe,
+ loginResponse!,
+ parseInt(twoFactorCode)
+ );
+
+ // Store access and refresh token using the context
+ if (validationResponse.token) {
+ // Store auth info
+ await authContext.login(credentials.username, validationResponse.token.token, validationResponse.token.refreshToken);
+ } else {
+ throw new Error('Login failed -- no token returned');
+ }
+
+ // Make another API call trying to get latest vault
+ const vaultResponseJson = await webApi.get('Vault') as VaultResponse;
+
+ // Initialize the SQLite context with the new vault data.
+ await dbContext.initializeDatabase(vaultResponseJson, passwordHashBase64);
+
+ // Reset 2FA state and login response as it's no longer needed
+ setTwoFactorRequired(false);
+ setTwoFactorCode('');
+ setPasswordHashString(null);
+ setPasswordHashBase64(null);
+ setLoginResponse(null);
+ hideLoading();
+ } catch (err) {
+ setError('Invalid authentication code. Please try again.');
+ console.error('2FA error:', err);
+ hideLoading();
+ }
+ };
+
/**
* Handle change
*/
@@ -97,6 +167,45 @@ const Login: React.FC = () => {
}));
};
+ if (twoFactorRequired) {
+ return (
+ <div className="max-w-md">
+ <form onSubmit={handleTwoFactorSubmit} className="bg-white dark:bg-gray-700 w-full shadow-md rounded px-8 pt-6 pb-8 mb-4">
+ {error && (
+ <div className="mb-4 text-red-500 dark:text-red-400 text-sm">
+ {error}
+ </div>
+ )}
+ <div className="mb-6">
+ <p className="text-gray-700 dark:text-gray-200 mb-4">
+ Please enter the authentication code from your authenticator app.
+ </p>
+ <label className="block text-gray-700 dark:text-gray-200 text-sm font-bold mb-2" htmlFor="twoFactorCode">
+ Authentication Code
+ </label>
+ <input
+ className="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 dark:text-gray-200 dark:bg-gray-800 dark:border-gray-600 leading-tight focus:outline-none focus:shadow-outline"
+ id="twoFactorCode"
+ type="text"
+ value={twoFactorCode}
+ onChange={(e) => setTwoFactorCode(e.target.value)}
+ placeholder="Enter 6-digit code"
+ required
+ />
+ </div>
+ <div className="flex w-full">
+ <Button type="submit">
+ Verify
+ </Button>
+ </div>
+ <p className="text-xs text-gray-500 dark:text-gray-400 mt-4 text-center">
+ Note: if you don&apos;t have access to your authenticator device, you can reset your 2FA with a recovery code by logging in via the website.
+ </p>
+ </form>
+ </div>
+ );
+ }
+
return (
<div className="max-w-md">
<form onSubmit={handleSubmit} className="bg-white dark:bg-gray-700 w-full shadow-md rounded px-8 pt-6 pb-8 mb-4">
diff --git a/browser-extensions/chrome/src/app/pages/Unlock.tsx b/browser-extensions/chrome/src/app/pages/Unlock.tsx
index d448124f8..e4aca6bca 100644
--- a/browser-extensions/chrome/src/app/pages/Unlock.tsx
+++ b/browser-extensions/chrome/src/app/pages/Unlock.tsx
@@ -85,7 +85,7 @@ const Unlock: React.FC = () => {
<form onSubmit={handleSubmit} className="bg-white dark:bg-gray-700 w-full shadow-md rounded px-8 pt-6 pb-8 mb-4">
<div className="flex space-x-4 mb-6">
<img className="w-8 h-8 rounded-full" src="/assets/images/avatar.webp" alt="User avatar" />
- <h2 className="text-2xl font-bold text-gray-900 dark:text-white">{authContext.username}</h2>
+ <h2 className="text-2xl font-bold text-gray-900 dark:text-white break-all overflow-hidden">{authContext.username}</h2>
</div>
<p className="text-base text-gray-500 dark:text-gray-200 mb-6">
diff --git a/browser-extensions/chrome/src/app/utils/SrpUtility.tsx b/browser-extensions/chrome/src/app/utils/SrpUtility.tsx
index de79613f2..e26099547 100644
--- a/browser-extensions/chrome/src/app/utils/SrpUtility.tsx
+++ b/browser-extensions/chrome/src/app/utils/SrpUtility.tsx
@@ -1,16 +1,7 @@
import srp from 'secure-remote-password/client'
-import { WebApiService } from './WebApiService';
-import { LoginRequest, LoginResponse } from '../types/webapi/Login';
-import { ValidateLoginRequest } from '../types/webapi/ValidateLogin';
-
-type ValidateLoginResponse = {
- requiresTwoFactor: boolean;
- token?: {
- token: string;
- refreshToken: string;
- };
- serverSessionProof: string;
-}
+import { WebApiService } from '../../shared/WebApiService';
+import { LoginRequest, LoginResponse } from '../../shared/types/webapi/Login';
+import { ValidateLoginRequest, ValidateLoginRequest2Fa, ValidateLoginResponse } from '../../shared/types/webapi/ValidateLogin';
/**
* Utility class for SRP authentication operations.
@@ -67,6 +58,40 @@ class SrpUtility {
clientSessionProof: sessionProof.proof,
});
}
+
+ /**
+ * 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> {
+ // Generate client ephemeral
+ const clientEphemeral = srp.generateEphemeral()
+
+ // Derive private key
+ const privateKey = srp.derivePrivateKey(loginResponse.salt, username, passwordHashString);
+
+ // Derive session
+ const sessionProof = srp.deriveSession(
+ clientEphemeral.secret,
+ loginResponse.serverEphemeral,
+ loginResponse.salt,
+ username,
+ privateKey
+ );
+
+ return this.webApiService.post<ValidateLoginRequest2Fa, ValidateLoginResponse>('Auth/validate-2fa', {
+ username: username.toLowerCase().trim(),
+ rememberMe: rememberMe,
+ clientPublicEphemeral: clientEphemeral.public,
+ clientSessionProof: sessionProof.proof,
+ code2Fa: code2Fa,
+ });
+ }
}
export default SrpUtility;
diff --git a/browser-extensions/chrome/src/shared/EncryptionUtility.tsx b/browser-extensions/chrome/src/shared/EncryptionUtility.tsx
index b83b7ff9f..30fb9054a 100644
--- a/browser-extensions/chrome/src/shared/EncryptionUtility.tsx
+++ b/browser-extensions/chrome/src/shared/EncryptionUtility.tsx
@@ -19,7 +19,7 @@ class EncryptionUtility {
salt: string,
encryptionType: string = 'Argon2id',
encryptionSettings: string = '{"Iterations":1,"MemorySize":1024,"DegreeOfParallelism":4}'
- ): Promise<string> {
+ ): Promise<Uint8Array> {
const settings = JSON.parse(encryptionSettings);
try {
diff --git a/browser-extensions/chrome/src/shared/types/webapi/ValidateLogin.ts b/browser-extensions/chrome/src/shared/types/webapi/ValidateLogin.ts
index 4b9910cb4..77c655f27 100644
--- a/browser-extensions/chrome/src/shared/types/webapi/ValidateLogin.ts
+++ b/browser-extensions/chrome/src/shared/types/webapi/ValidateLogin.ts
@@ -5,6 +5,14 @@ export type ValidateLoginRequest = {
clientSessionProof: string;
}
+export type ValidateLoginRequest2Fa = {
+ username: string;
+ code2Fa: number;
+ rememberMe: boolean;
+ clientPublicEphemeral: string;
+ clientSessionProof: string;
+}
+
export type ValidateLoginResponse = {
requiresTwoFactor: boolean;
token?: {