Skip to content

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

Add working basic 2FA login flow to client (#70)

Leendert de Borstf7865e5d9c9e
diff --git a/src/AliasVault.Api/Controllers/AuthController.cs b/src/AliasVault.Api/Controllers/AuthController.cs
index f341e88ac..0465983a0 100644
--- a/src/AliasVault.Api/Controllers/AuthController.cs
+++ b/src/AliasVault.Api/Controllers/AuthController.cs
@@ -11,6 +11,7 @@ using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Security.Cryptography;
using System.Text;
+using System.Text.Encodings.Web;
using AliasServerDb;
using AliasVault.Shared.Models;
using AliasVault.Shared.Models.WebApi;
@@ -32,16 +33,22 @@ using Microsoft.IdentityModel.Tokens;
/// <param name="signInManager">SignInManager instance.</param>
/// <param name="configuration">IConfiguration instance.</param>
/// <param name="cache">IMemoryCache instance for persisting SRP values during multi-step login process.</param>
-/// <param name="timeProvider">ITimeProvider instance. This returns the time which can be mutated for testing..</param>
+/// <param name="timeProvider">ITimeProvider instance. This returns the time which can be mutated for testing.</param>
+/// <param name="urlEncoder">UrlEncoder instance.</param>
[Route("api/v{version:apiVersion}/[controller]")]
[ApiController]
[ApiVersion("1")]
-public class AuthController(IDbContextFactory<AliasServerDbContext> dbContextFactory, UserManager<AliasVaultUser> userManager, SignInManager<AliasVaultUser> signInManager, IConfiguration configuration, IMemoryCache cache, ITimeProvider timeProvider) : ControllerBase
+public class AuthController(IDbContextFactory<AliasServerDbContext> dbContextFactory, UserManager<AliasVaultUser> userManager, SignInManager<AliasVaultUser> signInManager, IConfiguration configuration, IMemoryCache cache, ITimeProvider timeProvider, UrlEncoder urlEncoder) : ControllerBase
{
/// <summary>
/// Error message for invalid username or password.
/// </summary>
- public static readonly string[] InvalidUsernameOrPasswordError = ["Invalid username or password. Please try again."];
+ private static readonly string[] InvalidUsernameOrPasswordError = ["Invalid username or password. Please try again."];
+
+ /// <summary>
+ /// Error message for invalid 2-factor authentication code.
+ /// </summary>
+ private static readonly string[] Invalid2FaCode = ["Invalid authenticator code."];
/// <summary>
/// Login endpoint used to process login attempt using credentials.
@@ -95,11 +102,65 @@ public class AuthController(IDbContextFactory<AliasServerDbContext> dbContextFac
user.Verifier,
model.ClientSessionProof);
- // If above does not throw an exception., then the client's proof is valid, and we can issue the JWT token.
+ // If above does not throw an exception., then the client's proof is valid. Next check if 2FA is required.
+ // If 2FA is required, return that status and no token yet.
+ if (user.TwoFactorEnabled)
+ {
+ return Ok(new ValidateLoginResponse(true, string.Empty, null));
+ }
+
+ // If 2FA is not required, return the token immediately.
var tokenModel = await GenerateNewTokensForUser(user);
+ return Ok(new ValidateLoginResponse(false, serverSession.Proof, tokenModel));
+ }
+ catch
+ {
+ return BadRequest(ServerValidationErrorResponse.Create(InvalidUsernameOrPasswordError, 400));
+ }
+ }
- // Return server proof for optional client check and token.
- return Ok(new ValidateLoginResponse(serverSession.Proof, tokenModel));
+ /// <summary>
+ /// Validate login including two factor authentication code check.
+ /// </summary>
+ /// <param name="model">ValidateLoginRequest2Fa model.</param>
+ /// <returns>Task.</returns>
+ [HttpPost("validate-2fa")]
+ public async Task<IActionResult> Validate2Fa([FromBody] ValidateLoginRequest2Fa model)
+ {
+ var user = await userManager.FindByNameAsync(model.Username);
+ if (user == null)
+ {
+ return BadRequest(ServerValidationErrorResponse.Create(InvalidUsernameOrPasswordError, 400));
+ }
+
+ if (!cache.TryGetValue(model.Username, out var serverSecretEphemeral) || serverSecretEphemeral is not string)
+ {
+ return BadRequest(ServerValidationErrorResponse.Create(InvalidUsernameOrPasswordError, 400));
+ }
+
+ try
+ {
+ var serverSession = Cryptography.Srp.DeriveSessionServer(
+ serverSecretEphemeral.ToString() ?? string.Empty,
+ model.ClientPublicEphemeral,
+ user.Salt,
+ model.Username,
+ user.Verifier,
+ model.ClientSessionProof);
+
+ // If above does not throw an exception., then the client's proof is valid. Next check 2-factor code.
+
+ // Verify 2-factor code.
+ var result = await userManager.VerifyTwoFactorTokenAsync(user, userManager.Options.Tokens.AuthenticatorTokenProvider, model.Code2Fa);
+
+ if (!result)
+ {
+ return BadRequest(ServerValidationErrorResponse.Create(Invalid2FaCode, 400));
+ }
+
+ // Generate and return the JWT token.
+ var tokenModel = await GenerateNewTokensForUser(user);
+ return Ok(new ValidateLoginResponse(false, serverSession.Proof, tokenModel));
}
catch
{
@@ -159,6 +220,59 @@ public class AuthController(IDbContextFactory<AliasServerDbContext> dbContextFac
return Ok(new TokenModel() { Token = token, RefreshToken = newRefreshToken });
}
+ /// <summary>
+ /// Enable two-factor authentication for a user.
+ /// </summary>
+ /// <returns>Task.</returns>
+ [HttpPost("enable-2fa")]
+ public async Task<IActionResult> EnableTwoFactor()
+ {
+ var user = await userManager.GetUserAsync(User);
+ if (user == null)
+ {
+ return NotFound();
+ }
+
+ var authenticatorKey = await userManager.GetAuthenticatorKeyAsync(user);
+ if (string.IsNullOrEmpty(authenticatorKey))
+ {
+ await userManager.ResetAuthenticatorKeyAsync(user);
+ authenticatorKey = await userManager.GetAuthenticatorKeyAsync(user);
+ }
+
+ var encodedKey = urlEncoder.Encode(authenticatorKey!);
+ var qrCodeUrl = $"otpauth://totp/{urlEncoder.Encode("AliasVault WASM")}:{urlEncoder.Encode(user.UserName!)}?secret={encodedKey}&issuer={urlEncoder.Encode("AliasVault WASM")}";
+
+ return Ok(new { Secret = authenticatorKey, QrCodeUrl = qrCodeUrl });
+ }
+
+ /// <summary>
+ /// Verify two-factor authentication setup.
+ /// </summary>
+ /// <param name="code">Code to verify if 2fa successfully works.</param>
+ /// <returns>Task.</returns>
+ [HttpPost("verify-2fa")]
+ public async Task<IActionResult> VerifyTwoFactorSetup([FromBody] string code)
+ {
+ var user = await userManager.GetUserAsync(User);
+ if (user == null)
+ {
+ return NotFound();
+ }
+
+ var isValid = await userManager.VerifyTwoFactorTokenAsync(user, userManager.Options.Tokens.AuthenticatorTokenProvider, code);
+
+ if (isValid)
+ {
+ await userManager.SetTwoFactorEnabledAsync(user, true);
+ return Ok();
+ }
+ else
+ {
+ return BadRequest("Invalid code.");
+ }
+ }
+
/// <summary>
/// Revoke endpoint used to revoke a refresh token.
/// </summary>
diff --git a/src/AliasVault.Api/Properties/launchSettings.json b/src/AliasVault.Api/Properties/launchSettings.json
index 4c963eb19..0d7629f45 100644
--- a/src/AliasVault.Api/Properties/launchSettings.json
+++ b/src/AliasVault.Api/Properties/launchSettings.json
@@ -6,7 +6,8 @@
"launchUrl": "swagger",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development",
- "JWT_KEY": "12345678901234567890123456789012"
+ "JWT_KEY": "12345678901234567890123456789012",
+ "DATA_PROTECTION_CERT_PASS": "Development"
},
"dotnetRunMessages": true,
"applicationUrl": "http://localhost:5092"
diff --git a/src/AliasVault.Client/Auth/Pages/Base/LoginBase.cs b/src/AliasVault.Client/Auth/Pages/Base/LoginBase.cs
index 670b9ab53..08da66b96 100644
--- a/src/AliasVault.Client/Auth/Pages/Base/LoginBase.cs
+++ b/src/AliasVault.Client/Auth/Pages/Base/LoginBase.cs
@@ -7,13 +7,9 @@
namespace AliasVault.Client.Auth.Pages.Base;
-using System.Net.Http.Json;
-using System.Text.Json;
using AliasVault.Client.Services.Auth;
using AliasVault.Shared.Models.WebApi;
-using AliasVault.Shared.Models.WebApi.Auth;
using Blazored.LocalStorage;
-using Cryptography;
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Authorization;
using Microsoft.JSInterop;
@@ -93,91 +89,4 @@ public class LoginBase : OwningComponentBase
return returnErrors;
}
-
- /// <summary>
- /// Gets the username from the authentication state asynchronously.
- /// </summary>
- /// <param name="username">Username.</param>
- /// <param name="password">Password.</param>
- /// <returns>List of errors if something went wrong.</returns>
- protected async Task<List<string>> ProcessLoginAsync(string username, string password)
- {
- // Sanitize username
- username = username.ToLowerInvariant().Trim();
-
- // Send request to server with email to get server ephemeral public key.
- var result = await Http.PostAsJsonAsync("api/v1/Auth/login", new LoginRequest(username));
- var responseContent = await result.Content.ReadAsStringAsync();
-
- if (!result.IsSuccessStatusCode)
- {
- return ParseResponse(responseContent);
- }
-
- var loginResponse = JsonSerializer.Deserialize<LoginResponse>(responseContent);
- if (loginResponse == null)
- {
- return
- [
- "An error occurred while processing the login request.",
- ];
- }
-
- // 3. Client derives shared session key.
- byte[] passwordHash = await Encryption.DeriveKeyFromPasswordAsync(password, loginResponse.Salt);
- var passwordHashString = BitConverter.ToString(passwordHash).Replace("-", string.Empty);
-
- var clientEphemeral = Srp.GenerateEphemeralClient();
- var privateKey = Srp.DerivePrivateKey(loginResponse.Salt, username, passwordHashString);
- var clientSession = Srp.DeriveSessionClient(
- privateKey,
- clientEphemeral.Secret,
- loginResponse.ServerEphemeral,
- loginResponse.Salt,
- username);
-
- // 4. Client sends proof of session key to server.
- result = await Http.PostAsJsonAsync("api/v1/Auth/validate", new ValidateLoginRequest(username, clientEphemeral.Public, clientSession.Proof));
- responseContent = await result.Content.ReadAsStringAsync();
-
- if (!result.IsSuccessStatusCode)
- {
- return ParseResponse(responseContent);
- }
-
- var validateLoginResponse = JsonSerializer.Deserialize<ValidateLoginResponse>(responseContent);
- if (validateLoginResponse == null)
- {
- return
- [
- "An error occurred while processing the login request.",
- ];
- }
-
- // 5. Client verifies proof.
- Srp.VerifySession(clientEphemeral.Public, clientSession, validateLoginResponse.ServerSessionProof);
-
- // Store the tokens in local storage.
- await AuthService.StoreAccessTokenAsync(validateLoginResponse.Token.Token);
- await AuthService.StoreRefreshTokenAsync(validateLoginResponse.Token.RefreshToken);
-
- // Store the encryption key in memory.
- AuthService.StoreEncryptionKey(passwordHash);
-
- await AuthStateProvider.GetAuthenticationStateAsync();
- GlobalNotificationService.ClearMessages();
-
- // Redirect to the page the user was trying to access before if set.
- var localStorageReturnUrl = await LocalStorage.GetItemAsync<string>("returnUrl");
- if (!string.IsNullOrEmpty(localStorageReturnUrl))
- {
- NavigationManager.NavigateTo(localStorageReturnUrl);
- }
- else
- {
- NavigationManager.NavigateTo("/");
- }
-
- return [];
- }
}
diff --git a/src/AliasVault.Client/Auth/Pages/Login.razor b/src/AliasVault.Client/Auth/Pages/Login.razor
index 5fa178136..16f29d08f 100644
--- a/src/AliasVault.Client/Auth/Pages/Login.razor
+++ b/src/AliasVault.Client/Auth/Pages/Login.razor
@@ -2,49 +2,96 @@
@inherits AliasVault.Client.Auth.Pages.Base.LoginBase
@layout Auth.Layout.MainLayout
@attribute [AllowAnonymous]
+@using System.Text.Json
@using AliasVault.Shared.Models
@using AliasVault.Client.Auth.Components
+@using AliasVault.Shared.Models.WebApi.Auth
+@using Cryptography
+@using SecureRemotePassword
-<h2 class="text-2xl font-bold text-gray-900 dark:text-white">
- Sign in to AliasVault
-</h2>
+@if (ShowTwoFactorAuthStep)
+{
+ <h2 class="text-2xl font-bold text-gray-900 dark:text-white mb-4">
+ Two-factor authentication
+ </h2>
-<FullScreenLoadingIndicator @ref="LoadingIndicator" />
-<ServerValidationErrors @ref="ServerValidationErrors" />
+ <ServerValidationErrors @ref="ServerValidationErrors" />
-<EditForm Model="LoginModel" OnValidSubmit="HandleLogin" class="mt-8 space-y-6">
- <DataAnnotationsValidator/>
- <div>
- <label asp-for="Input.Email" class="block mb-2 text-sm font-medium text-gray-900 dark:text-white">Your username or email</label>
- <InputTextField id="email" @bind-Value="LoginModel.Username" placeholder="name / [email protected]" />
- <ValidationMessage For="() => LoginModel.Username"/>
- </div>
- <div>
- <label asp-for="Input.Password" class="block mb-2 text-sm font-medium text-gray-900 dark:text-white">Your password</label>
- <InputTextField id="password" @bind-Value="LoginModel.Password" type="password" placeholder="••••••••" />
- <ValidationMessage For="() => LoginModel.Password"/>
+ <p class="text-gray-700 dark:text-gray-300 mb-6">Your login is protected with an authenticator app. Enter your authenticator code below.</p>
+ <div class="w-full">
+ <EditForm Model="LoginModel2Fa" FormName="login-with-2fa" OnValidSubmit="Handle2Fa" method="post" class="space-y-6">
+ <DataAnnotationsValidator/>
+ <ValidationSummary class="text-red-600 dark:text-red-400" role="alert"/>
+ <div>
+ <label for="two-factor-code" class="block mb-2 text-sm font-medium text-gray-900 dark:text-white">Authenticator code</label>
+ <InputText @bind-Value="LoginModel2Fa.TwoFactorCode" id="two-factor-code" class="bg-gray-50 border border-gray-300 text-gray-900 sm:text-sm rounded-lg focus:ring-primary-600 focus:border-primary-600 block w-full p-2.5 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white dark:focus:ring-blue-500 dark:focus:border-blue-500" autocomplete="off"/>
+ <ValidationMessage For="() => LoginModel2Fa.TwoFactorCode" class="text-red-600 dark:text-red-400 text-sm mt-1"/>
+ </div>
+ <div class="flex items-start">
+ <div class="flex items-center h-5">
+ <InputCheckbox @bind-Value="LoginModel2Fa.RememberMachine" id="remember-machine" class="w-4 h-4 border border-gray-300 rounded bg-gray-50 focus:ring-3 focus:ring-primary-300 dark:bg-gray-700 dark:border-gray-600 dark:focus:ring-primary-600 dark:ring-offset-gray-800"/>
+ </div>
+ <div class="ml-3 text-sm">
+ <label for="remember-machine" class="font-medium text-gray-900 dark:text-white">Remember this machine</label>
+ </div>
+ </div>
+ <button type="submit" class="w-full text-white bg-primary-600 hover:bg-primary-700 focus:ring-4 focus:outline-none focus:ring-primary-300 font-medium rounded-lg text-sm px-5 py-2.5 text-center dark:bg-primary-600 dark:hover:bg-primary-700 dark:focus:ring-primary-800">Log in</button>
+ </EditForm>
</div>
+ <p class="mt-6 text-sm text-gray-700 dark:text-gray-300">
+ Don't have access to your authenticator device? You can
+ <a href="user/loginWithRecoveryCode" class="text-primary-600 hover:underline dark:text-primary-500">log in with a recovery code</a>.
+ </p>
+}
+else
+{
+ <h2 class="text-2xl font-bold text-gray-900 dark:text-white">
+ Sign in to AliasVault
+ </h2>
+
+ <FullScreenLoadingIndicator @ref="LoadingIndicator"/>
+ <ServerValidationErrors @ref="ServerValidationErrors"/>
- <div class="flex items-start">
- <div class="flex items-center h-5">
- <input id="remember" aria-describedby="remember" name="remember" type="checkbox" class="w-4 h-4 border-gray-300 rounded bg-gray-50 focus:ring-3 focus:ring-primary-300 dark:focus:ring-primary-600 dark:ring-offset-gray-800 dark:bg-gray-700 dark:border-gray-600">
+ <EditForm Model="LoginModel" OnValidSubmit="HandleLogin" class="mt-8 space-y-6">
+ <DataAnnotationsValidator/>
+ <div>
+ <label asp-for="Input.Email" class="block mb-2 text-sm font-medium text-gray-900 dark:text-white">Your username or email</label>
+ <InputTextField id="email" @bind-Value="LoginModel.Username" placeholder="name / [email protected]"/>
+ <ValidationMessage For="() => LoginModel.Username"/>
</div>
- <div class="ml-3 text-sm">
- <label for="remember" class="font-medium text-gray-900 dark:text-white">Remember me</label>
+ <div>
+ <label asp-for="Input.Password" class="block mb-2 text-sm font-medium text-gray-900 dark:text-white">Your password</label>
+ <InputTextField id="password" @bind-Value="LoginModel.Password" type="password" placeholder="••••••••"/>
+ <ValidationMessage For="() => LoginModel.Password"/>
</div>
- <a href="/user/forgot-password" class="ml-auto text-sm text-primary-700 hover:underline dark:text-primary-500">Lost Password?</a>
- </div>
- <button type="submit" class="w-full px-5 py-3 text-base font-medium text-center text-white bg-primary-700 rounded-lg hover:bg-primary-800 focus:ring-4 focus:ring-primary-300 sm:w-auto dark:bg-primary-600 dark:hover:bg-primary-700 dark:focus:ring-primary-800">Login to your account</button>
- <div class="text-sm font-medium text-gray-500 dark:text-gray-400">
- Not registered? <a href="/user/register" class="text-primary-700 hover:underline dark:text-primary-500">Create account</a>
- </div>
-</EditForm>
+ <div class="flex items-start">
+ <div class="flex items-center h-5">
+ <input id="remember" aria-describedby="remember" name="remember" type="checkbox" class="w-4 h-4 border-gray-300 rounded bg-gray-50 focus:ring-3 focus:ring-primary-300 dark:focus:ring-primary-600 dark:ring-offset-gray-800 dark:bg-gray-700 dark:border-gray-600">
+ </div>
+ <div class="ml-3 text-sm">
+ <label for="remember" class="font-medium text-gray-900 dark:text-white">Remember me</label>
+ </div>
+ <a href="/user/forgot-password" class="ml-auto text-sm text-primary-700 hover:underline dark:text-primary-500">Lost Password?</a>
+ </div>
+
+ <button type="submit" class="w-full px-5 py-3 text-base font-medium text-center text-white bg-primary-700 rounded-lg hover:bg-primary-800 focus:ring-4 focus:ring-primary-300 sm:w-auto dark:bg-primary-600 dark:hover:bg-primary-700 dark:focus:ring-primary-800">Login to your account</button>
+ <div class="text-sm font-medium text-gray-500 dark:text-gray-400">
+ Not registered? <a href="/user/register" class="text-primary-700 hover:underline dark:text-primary-500">Create account</a>
+ </div>
+ </EditForm>
+}
@code {
private readonly LoginModel LoginModel = new();
+ private readonly LoginModel2Fa LoginModel2Fa = new();
private FullScreenLoadingIndicator LoadingIndicator = new();
private ServerValidationErrors ServerValidationErrors = new();
+ private bool ShowTwoFactorAuthStep = false;
+
+ private SrpEphemeral ClientEphemeral = new();
+ private SrpSession ClientSession = new();
+ private byte[] PasswordHash = [];
/// <inheritdoc />
protected override async Task OnInitializedAsync()
@@ -64,7 +111,7 @@
try
{
- var errors = await ProcessLoginAsync(LoginModel.Username, LoginModel.Password);
+ var errors = await ProcessLoginAsync();
foreach (var error in errors)
{
ServerValidationErrors.AddError(error);
@@ -88,4 +135,158 @@
LoadingIndicator.Hide();
}
}
+
+ private async Task Handle2Fa()
+ {
+ LoadingIndicator.Show();
+ ServerValidationErrors.Clear();
+
+ try
+ {
+ // Sanitize username
+ var username = LoginModel.Username.ToLowerInvariant().Trim();
+
+ // Validate 2-factor auth code auth and login
+ var result = await Http.PostAsJsonAsync("api/v1/Auth/validate-2fa", new ValidateLoginRequest2Fa(username, ClientEphemeral.Public, ClientSession.Proof, LoginModel2Fa.TwoFactorCode));
+ var responseContent = await result.Content.ReadAsStringAsync();
+
+ if (!result.IsSuccessStatusCode)
+ {
+ foreach (var error in ParseResponse(responseContent))
+ {
+ ServerValidationErrors.AddError(error);
+ return;
+ }
+ }
+
+ var validateLoginResponse = JsonSerializer.Deserialize<ValidateLoginResponse>(responseContent);
+ if (validateLoginResponse == null)
+ {
+ ServerValidationErrors.AddError("An error occurred while processing the login request.");
+ return;
+ }
+
+ var errors = await ProcessLoginVerify(validateLoginResponse);
+ foreach (var error in errors)
+ {
+ ServerValidationErrors.AddError(error);
+ }
+ }
+#if DEBUG
+ catch (Exception ex)
+ {
+ // If in debug mode show the actual exception.
+ ServerValidationErrors.AddError(ex.ToString());
+ }
+#else
+ catch
+ {
+ // If in release mode show a generic error.
+ ServerValidationErrors.AddError("An error occurred while processing the login request. Try again (later).");
+ }
+#endif
+ finally
+ {
+ LoadingIndicator.Hide();
+ }
+ }
+
+ /// <summary>
+ /// Gets the username from the authentication state asynchronously.
+ /// </summary>
+ /// <returns>List of errors if something went wrong.</returns>
+ protected async Task<List<string>> ProcessLoginAsync()
+ {
+ // Sanitize username
+ var username = LoginModel.Username.ToLowerInvariant().Trim();
+
+ // Send request to server with email to get server ephemeral public key.
+ var result = await Http.PostAsJsonAsync("api/v1/Auth/login", new LoginRequest(username));
+ var responseContent = await result.Content.ReadAsStringAsync();
+
+ if (!result.IsSuccessStatusCode)
+ {
+ return ParseResponse(responseContent);
+ }
+
+ var loginResponse = JsonSerializer.Deserialize<LoginResponse>(responseContent);
+ if (loginResponse == null)
+ {
+ return
+ [
+ "An error occurred while processing the login request.",
+ ];
+ }
+
+ // 3. Client derives shared session key.
+ PasswordHash = await Encryption.DeriveKeyFromPasswordAsync(LoginModel.Password, loginResponse.Salt);
+ var passwordHashString = BitConverter.ToString(PasswordHash).Replace("-", string.Empty);
+
+ ClientEphemeral = Srp.GenerateEphemeralClient();
+ var privateKey = Srp.DerivePrivateKey(loginResponse.Salt, username, passwordHashString);
+ ClientSession = Srp.DeriveSessionClient(
+ privateKey,
+ ClientEphemeral.Secret,
+ loginResponse.ServerEphemeral,
+ loginResponse.Salt,
+ username);
+
+ // 4. Client sends proof of session key to server.
+ result = await Http.PostAsJsonAsync("api/v1/Auth/validate", new ValidateLoginRequest(username, ClientEphemeral.Public, ClientSession.Proof));
+ responseContent = await result.Content.ReadAsStringAsync();
+
+ if (!result.IsSuccessStatusCode)
+ {
+ return ParseResponse(responseContent);
+ }
+
+ var validateLoginResponse = JsonSerializer.Deserialize<ValidateLoginResponse>(responseContent);
+ if (validateLoginResponse == null)
+ {
+ return
+ [
+ "An error occurred while processing the login request.",
+ ];
+ }
+
+ // Check if 2FA is required, if yes, show 2FA step.
+ if (validateLoginResponse.RequiresTwoFactor)
+ {
+ ShowTwoFactorAuthStep = true;
+ StateHasChanged();
+ return [];
+ }
+
+ return await ProcessLoginVerify(validateLoginResponse);
+ }
+
+ private async Task<List<string>> ProcessLoginVerify(ValidateLoginResponse validateLoginResponse)
+ {
+ // If not, then continue with login as normal and verify the proof.
+ // 5. Client verifies proof.
+ Srp.VerifySession(ClientEphemeral.Public, ClientSession, validateLoginResponse.ServerSessionProof);
+
+ // Store the tokens in local storage.
+ await AuthService.StoreAccessTokenAsync(validateLoginResponse.Token!.Token);
+ await AuthService.StoreRefreshTokenAsync(validateLoginResponse.Token!.RefreshToken);
+
+ // Store the encryption key in memory.
+ AuthService.StoreEncryptionKey(PasswordHash);
+
+ await AuthStateProvider.GetAuthenticationStateAsync();
+ GlobalNotificationService.ClearMessages();
+
+ // Redirect to the page the user was trying to access before if set.
+ var localStorageReturnUrl = await LocalStorage.GetItemAsync<string>("returnUrl");
+ if (!string.IsNullOrEmpty(localStorageReturnUrl))
+ {
+ NavigationManager.NavigateTo(localStorageReturnUrl);
+ }
+ else
+ {
+ NavigationManager.NavigateTo("/");
+ }
+
+ return [];
+ }
}
diff --git a/src/AliasVault.Client/Auth/Pages/Unlock.razor b/src/AliasVault.Client/Auth/Pages/Unlock.razor
index 454114761..b958a776e 100644
--- a/src/AliasVault.Client/Auth/Pages/Unlock.razor
+++ b/src/AliasVault.Client/Auth/Pages/Unlock.razor
@@ -1,8 +1,11 @@
@page "/unlock"
@inherits AliasVault.Client.Auth.Pages.Base.LoginBase
@layout Auth.Layout.MainLayout
+@using System.Text.Json
@using AliasVault.Shared.Models
@using AliasVault.Client.Auth.Components
+@using AliasVault.Shared.Models.WebApi.Auth
+@using Cryptography
<div class="flex space-x-4">
<img class="w-8 h-8 rounded-full" src="/img/avatar.webp" alt="Bonnie image">
@@ -75,12 +78,42 @@
try
{
- var errors = await ProcessLoginAsync(Email, UnlockModel.Password);
- foreach (var error in errors)
+ // Send request to server with email to get user salt.
+ var result = await Http.PostAsJsonAsync("api/v1/Auth/login", new LoginRequest(Email));
+ var responseContent = await result.Content.ReadAsStringAsync();
+
+ if (!result.IsSuccessStatusCode)
+ {
+ var errors = ParseResponse(responseContent);
+ foreach (var error in errors)
+ {
+ ServerValidationErrors.AddError(error);
+ }
+ return;
+ }
+
+ var loginResponse = JsonSerializer.Deserialize<LoginResponse>(responseContent);
+ if (loginResponse == null)
+ {
+ ServerValidationErrors.AddError("An error occurred while processing the unlock request.");
+ }
+
+ // 3. Client derives shared session key.
+ byte[] passwordHash = await Encryption.DeriveKeyFromPasswordAsync(UnlockModel.Password, loginResponse!.Salt);
+
+ // Store the encryption key in memory.
+ AuthService.StoreEncryptionKey(passwordHash);
+
+ // Redirect to the page the user was trying to access before if set.
+ var localStorageReturnUrl = await LocalStorage.GetItemAsync<string>("returnUrl");
+ if (!string.IsNullOrEmpty(localStorageReturnUrl))
+ {
+ NavigationManager.NavigateTo(localStorageReturnUrl);
+ }
+ else
{
- ServerValidationErrors.AddError(error);
+ NavigationManager.NavigateTo("/");
}
- StateHasChanged();
}
#if DEBUG
catch (Exception ex)
diff --git a/src/AliasVault.Client/Main/Layout/TopMenu.razor b/src/AliasVault.Client/Main/Layout/TopMenu.razor
index 23345377c..719b6269f 100644
--- a/src/AliasVault.Client/Main/Layout/TopMenu.razor
+++ b/src/AliasVault.Client/Main/Layout/TopMenu.razor
@@ -45,6 +45,9 @@
<li>
<a href="/settings/general" class="block py-2 px-4 text-sm hover:bg-gray-100 dark:hover:bg-gray-600 dark:text-gray-400 dark:hover:text-white">General settings</a>
</li>
+ <li>
+ <a href="/settings/totp" class="block py-2 px-4 text-sm hover:bg-gray-100 dark:hover:bg-gray-600 dark:text-gray-400 dark:hover:text-white">2FA settings</a>
+ </li>
<li>
<a href="/settings/vault" class="block py-2 px-4 text-sm hover:bg-gray-100 dark:hover:bg-gray-600 dark:text-gray-400 dark:hover:text-white">Vault settings</a>
</li>
diff --git a/src/AliasVault.Client/Main/Pages/Settings/Totp.razor b/src/AliasVault.Client/Main/Pages/Settings/Totp.razor
new file mode 100644
index 000000000..216d017e8
--- /dev/null
+++ b/src/AliasVault.Client/Main/Pages/Settings/Totp.razor
@@ -0,0 +1,91 @@
+@page "/settings/totp"
+@inherits MainBase
+@inject HttpClient Http
+
+<div class="max-w-md mx-auto mt-10 p-6 bg-white rounded-lg shadow-md">
+ <h3 class="text-2xl font-bold text-gray-800 mb-6">Set Up Two-Factor Authentication</h3>
+
+ @if (!string.IsNullOrEmpty(QrCodeUrl))
+ {
+ <div class="space-y-6">
+ <div id="authenticator-uri" data-url="@QrCodeUrl" class="flex justify-center">
+ <!-- QR code will be rendered here -->
+ </div>
+
+ <p class="text-sm text-gray-600 text-center">
+ Scan this QR code with your authenticator app or enter the following secret manually:
+ </p>
+ <p class="text-lg font-mono text-center bg-gray-100 p-2 rounded">@Secret</p>
+
+ <EditForm Model="@VerifyModel" OnValidSubmit="@VerifySetup" class="space-y-4">
+ <div>
+ <InputText id="verificationCode" @bind-Value="VerifyModel.Code"
+ class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
+ placeholder="Enter verification code" />
+ </div>
+ <button type="submit"
+ class="w-full bg-blue-500 text-white py-2 px-4 rounded-md hover:bg-blue-600 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2 transition duration-150 ease-in-out">
+ Verify and Enable
+ </button>
+ </EditForm>
+ </div>
+ }
+ else
+ {
+ <button @onclick="EnableTwoFactor"
+ class="w-full bg-green-500 text-white py-2 px-4 rounded-md hover:bg-green-600 focus:outline-none focus:ring-2 focus:ring-green-500 focus:ring-offset-2 transition duration-150 ease-in-out">
+ Enable Two-Factor Authentication
+ </button>
+ }
+</div>
+
+@code {
+ private string QrCodeUrl { get; set; } = string.Empty;
+ private string Secret { get; set; } = string.Empty;
+ private VerificationModel VerifyModel = new();
+
+ private async Task EnableTwoFactor()
+ {
+ var response = await Http.PostAsync("api/v1/Auth/enable-2fa", null);
+ if (response.IsSuccessStatusCode)
+ {
+ var result = await response.Content.ReadFromJsonAsync<TotpSetupResult>();
+
+ if (result != null)
+ {
+ QrCodeUrl = result.QrCodeUrl;
+ Secret = result.Secret;
+ StateHasChanged();
+ JsInteropService.GenerateQrCode("authenticator-uri");
+ }
+ }
+ }
+
+ private async Task VerifySetup()
+ {
+ var response = await Http.PostAsJsonAsync("api/v1/Auth/verify-2fa", VerifyModel.Code);
+ if (response.IsSuccessStatusCode)
+ {
+ // TOTP setup successful
+ // You might want to navigate the user or show a success message
+ GlobalNotificationService.AddSuccessMessage("Two-factor authentication is now successfully enabled. On your " +
+ "next login you will need to enter your 2FA code.");
+ NavigationManager.NavigateTo("/credentials");
+ }
+ else
+ {
+ // Handle error
+ }
+ }
+
+ private class TotpSetupResult
+ {
+ public string Secret { get; set; } = string.Empty;
+ public string QrCodeUrl { get; set; } = string.Empty;
+ }
+
+ private class VerificationModel
+ {
+ public string Code { get; set; } = string.Empty;
+ }
+}
diff --git a/src/AliasVault.Client/Services/JsInteropService.cs b/src/AliasVault.Client/Services/JsInteropService.cs
index 984b5ace9..81e37747a 100644
--- a/src/AliasVault.Client/Services/JsInteropService.cs
+++ b/src/AliasVault.Client/Services/JsInteropService.cs
@@ -124,4 +124,21 @@ public sealed class JsInteropService(IJSRuntime jsRuntime)
throw new CryptographicException("Decryption failed", ex);
}
}
+
+ /// <summary>
+ /// Generates a QR code.
+ /// </summary>
+ /// <param name="elementId">Element ID that contains data-url attribute which to generate QR code for.</param>
+ public async void GenerateQrCode(string elementId)
+ {
+ try
+ {
+ // Invoke the JavaScript function and get the result as a byte array
+ await jsRuntime.InvokeVoidAsync("generateQrCode", "authenticator-uri");
+ }
+ catch (JSException ex)
+ {
+ await Console.Error.WriteLineAsync($"JavaScript error: {ex.Message}");
+ }
+ }
}
diff --git a/src/AliasVault.Client/wwwroot/css/tailwind.css b/src/AliasVault.Client/wwwroot/css/tailwind.css
index fd0306c66..060a77b0a 100644
--- a/src/AliasVault.Client/wwwroot/css/tailwind.css
+++ b/src/AliasVault.Client/wwwroot/css/tailwind.css
@@ -600,10 +600,6 @@ video {
border-width: 0;
}
-.visible {
- visibility: visible;
-}
-
.static {
position: static;
}
@@ -701,16 +697,6 @@ video {
margin-bottom: 1rem;
}
-.my-6 {
- margin-top: 1.5rem;
- margin-bottom: 1.5rem;
-}
-
-.my-8 {
- margin-top: 2rem;
- margin-bottom: 2rem;
-}
-
.-ml-1 {
margin-left: -0.25rem;
}
@@ -735,6 +721,10 @@ video {
margin-bottom: 1.25rem;
}
+.mb-6 {
+ margin-bottom: 1.5rem;
+}
+
.mb-8 {
margin-bottom: 2rem;
}
@@ -751,10 +741,6 @@ video {
margin-left: auto;
}
-.mr-14 {
- margin-right: 3.5rem;
-}
-
.mr-2 {
margin-right: 0.5rem;
}
@@ -811,12 +797,8 @@ video {
margin-top: 2rem;
}
-.mb-10 {
- margin-bottom: 2.5rem;
-}
-
-.mb-6 {
- margin-bottom: 1.5rem;
+.mt-10 {
+ margin-top: 2.5rem;
}
.line-clamp-2 {
@@ -866,10 +848,6 @@ video {
height: 3rem;
}
-.h-24 {
- height: 6rem;
-}
-
.h-3 {
height: 0.75rem;
}
@@ -902,10 +880,6 @@ video {
height: 100%;
}
-.h-16 {
- height: 4rem;
-}
-
.w-1\/2 {
width: 50%;
}
@@ -934,10 +908,6 @@ video {
width: 1rem;
}
-.w-48 {
- width: 12rem;
-}
-
.w-5 {
width: 1.25rem;
}
@@ -970,18 +940,6 @@ video {
width: 100%;
}
-.w-80 {
- width: 20rem;
-}
-
-.w-16 {
- width: 4rem;
-}
-
-.w-11 {
- width: 2.75rem;
-}
-
.min-w-full {
min-width: 100%;
}
@@ -998,10 +956,6 @@ video {
max-width: 36rem;
}
-.max-w-lg {
- max-width: 32rem;
-}
-
.flex-shrink-0 {
flex-shrink: 0;
}
@@ -1094,10 +1048,6 @@ video {
align-items: center;
}
-.items-baseline {
- align-items: baseline;
-}
-
.justify-start {
justify-content: flex-start;
}
@@ -1168,18 +1118,6 @@ video {
margin-bottom: calc(1.5rem * var(--tw-space-y-reverse));
}
-.space-x-3 > :not([hidden]) ~ :not([hidden]) {
- --tw-space-x-reverse: 0;
- margin-right: calc(0.75rem * var(--tw-space-x-reverse));
- margin-left: calc(0.75rem * calc(1 - var(--tw-space-x-reverse)));
-}
-
-.space-y-12 > :not([hidden]) ~ :not([hidden]) {
- --tw-space-y-reverse: 0;
- margin-top: calc(3rem * calc(1 - var(--tw-space-y-reverse)));
- margin-bottom: calc(3rem * var(--tw-space-y-reverse));
-}
-
.divide-y > :not([hidden]) ~ :not([hidden]) {
--tw-divide-y-reverse: 0;
border-top-width: calc(1px * calc(1 - var(--tw-divide-y-reverse)));
@@ -1306,11 +1244,6 @@ video {
border-color: rgb(248 185 99 / var(--tw-border-opacity));
}
-.border-primary-500 {
- --tw-border-opacity: 1;
- border-color: rgb(244 149 65 / var(--tw-border-opacity));
-}
-
.border-primary-600 {
--tw-border-opacity: 1;
border-color: rgb(214 131 56 / var(--tw-border-opacity));
@@ -1321,6 +1254,11 @@ video {
background-color: rgb(59 130 246 / var(--tw-bg-opacity));
}
+.bg-blue-600 {
+ --tw-bg-opacity: 1;
+ background-color: rgb(37 99 235 / var(--tw-bg-opacity));
+}
+
.bg-gray-100 {
--tw-bg-opacity: 1;
background-color: rgb(243 244 246 / var(--tw-bg-opacity));
@@ -1361,21 +1299,11 @@ video {
background-color: rgb(31 41 55 / var(--tw-bg-opacity));
}
-.bg-gray-900 {
- --tw-bg-opacity: 1;
- background-color: rgb(17 24 39 / var(--tw-bg-opacity));
-}
-
.bg-green-50 {
--tw-bg-opacity: 1;
background-color: rgb(240 253 244 / var(--tw-bg-opacity));
}
-.bg-green-500 {
- --tw-bg-opacity: 1;
- background-color: rgb(34 197 94 / var(--tw-bg-opacity));
-}
-
.bg-green-600 {
--tw-bg-opacity: 1;
background-color: rgb(22 163 74 / var(--tw-bg-opacity));
@@ -1416,19 +1344,9 @@ video {
background-color: rgb(255 255 255 / var(--tw-bg-opacity));
}
-.bg-primary-500 {
- --tw-bg-opacity: 1;
- background-color: rgb(244 149 65 / var(--tw-bg-opacity));
-}
-
-.bg-blue-600 {
- --tw-bg-opacity: 1;
- background-color: rgb(37 99 235 / var(--tw-bg-opacity));
-}
-
-.bg-purple-600 {
+.bg-green-500 {
--tw-bg-opacity: 1;
- background-color: rgb(147 51 234 / var(--tw-bg-opacity));
+ background-color: rgb(34 197 94 / var(--tw-bg-opacity));
}
.bg-opacity-50 {
@@ -1557,6 +1475,10 @@ video {
padding-right: 0.75rem;
}
+.pt-10 {
+ padding-top: 2.5rem;
+}
+
.pt-16 {
padding-top: 4rem;
}
@@ -1577,26 +1499,6 @@ video {
padding-top: 2rem;
}
-.pl-4 {
- padding-left: 1rem;
-}
-
-.pt-10 {
- padding-top: 2.5rem;
-}
-
-.pt-20 {
- padding-top: 5rem;
-}
-
-.pt-24 {
- padding-top: 6rem;
-}
-
-.pt-9 {
- padding-top: 2.25rem;
-}
-
.text-left {
text-align: left;
}
@@ -1605,10 +1507,6 @@ video {
text-align: center;
}
-.text-right {
- text-align: right;
-}
-
.text-start {
text-align: start;
}
@@ -1617,11 +1515,20 @@ video {
vertical-align: middle;
}
+.font-mono {
+ font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, Liberation Mono, Courier New, monospace;
+}
+
.text-2xl {
font-size: 1.5rem;
line-height: 2rem;
}
+.text-3xl {
+ font-size: 1.875rem;
+ line-height: 2.25rem;
+}
+
.text-base {
font-size: 1rem;
line-height: 1.5rem;
@@ -1647,16 +1554,6 @@ video {
line-height: 1rem;
}
-.text-3xl {
- font-size: 1.875rem;
- line-height: 2.25rem;
-}
-
-.text-5xl {
- font-size: 3rem;
- line-height: 1;
-}
-
.font-bold {
font-weight: 700;
}
@@ -1677,10 +1574,6 @@ video {
font-weight: 600;
}
-.font-extrabold {
- font-weight: 800;
-}
-
.uppercase {
text-transform: uppercase;
}
@@ -1771,6 +1664,11 @@ video {
color: rgb(244 149 65 / var(--tw-text-opacity));
}
+.text-primary-600 {
+ --tw-text-opacity: 1;
+ color: rgb(214 131 56 / var(--tw-text-opacity));
+}
+
.text-primary-700 {
--tw-text-opacity: 1;
color: rgb(184 112 47 / var(--tw-text-opacity));
@@ -1791,18 +1689,9 @@ video {
color: rgb(255 255 255 / var(--tw-text-opacity));
}
-.text-primary-600 {
- --tw-text-opacity: 1;
- color: rgb(214 131 56 / var(--tw-text-opacity));
-}
-
-.text-green-400 {
+.text-red-600 {
--tw-text-opacity: 1;
- color: rgb(74 222 128 / var(--tw-text-opacity));
-}
-
-.underline {
- text-decoration-line: underline;
+ color: rgb(220 38 38 / var(--tw-text-opacity));
}
.opacity-25 {
@@ -1829,6 +1718,12 @@ video {
box-shadow: var(--tw-ring-offset-shadow, 0 0 #0000), var(--tw-ring-shadow, 0 0 #0000), var(--tw-shadow);
}
+.shadow-md {
+ --tw-shadow: 0 4px 6px -1px rgb(0 0 0 / 0.1), 0 2px 4px -2px rgb(0 0 0 / 0.1);
+ --tw-shadow-colored: 0 4px 6px -1px var(--tw-shadow-color), 0 2px 4px -2px var(--tw-shadow-color);
+ box-shadow: var(--tw-ring-offset-shadow, 0 0 #0000), var(--tw-ring-shadow, 0 0 #0000), var(--tw-shadow);
+}
+
.shadow-sm {
--tw-shadow: 0 1px 2px 0 rgb(0 0 0 / 0.05);
--tw-shadow-colored: 0 1px 2px 0 var(--tw-shadow-color);
@@ -1841,12 +1736,6 @@ video {
box-shadow: var(--tw-ring-offset-shadow, 0 0 #0000), var(--tw-ring-shadow, 0 0 #0000), var(--tw-shadow);
}
-.shadow-md {
- --tw-shadow: 0 4px 6px -1px rgb(0 0 0 / 0.1), 0 2px 4px -2px rgb(0 0 0 / 0.1);
- --tw-shadow-colored: 0 4px 6px -1px var(--tw-shadow-color), 0 2px 4px -2px var(--tw-shadow-color);
- box-shadow: var(--tw-ring-offset-shadow, 0 0 #0000), var(--tw-ring-shadow, 0 0 #0000), var(--tw-shadow);
-}
-
.outline-0 {
outline-width: 0px;
}
@@ -1917,6 +1806,11 @@ video {
background-color: rgb(249 250 251 / var(--tw-bg-opacity));
}
+.hover\:bg-gray-500:hover {
+ --tw-bg-opacity: 1;
+ background-color: rgb(107 114 128 / var(--tw-bg-opacity));
+}
+
.hover\:bg-gray-800:hover {
--tw-bg-opacity: 1;
background-color: rgb(31 41 55 / var(--tw-bg-opacity));
@@ -1957,14 +1851,9 @@ video {
background-color: rgb(153 27 27 / var(--tw-bg-opacity));
}
-.hover\:bg-purple-700:hover {
+.hover\:bg-green-600:hover {
--tw-bg-opacity: 1;
- background-color: rgb(126 34 206 / var(--tw-bg-opacity));
-}
-
-.hover\:bg-gray-500:hover {
- --tw-bg-opacity: 1;
- background-color: rgb(107 114 128 / var(--tw-bg-opacity));
+ background-color: rgb(22 163 74 / var(--tw-bg-opacity));
}
.hover\:from-primary-600:hover {
@@ -2021,10 +1910,6 @@ video {
text-decoration-line: underline;
}
-.hover\:no-underline:hover {
- text-decoration-line: none;
-}
-
.focus\:border-blue-500:focus {
--tw-border-opacity: 1;
border-color: rgb(59 130 246 / var(--tw-border-opacity));
@@ -2035,6 +1920,11 @@ video {
border-color: rgb(244 149 65 / var(--tw-border-opacity));
}
+.focus\:border-primary-600:focus {
+ --tw-border-opacity: 1;
+ border-color: rgb(214 131 56 / var(--tw-border-opacity));
+}
+
.focus\:outline-none:focus {
outline: 2px solid transparent;
outline-offset: 2px;
@@ -2092,9 +1982,14 @@ video {
--tw-ring-color: rgb(252 165 165 / var(--tw-ring-opacity));
}
-.focus\:ring-primary-200:focus {
+.focus\:ring-green-500:focus {
--tw-ring-opacity: 1;
- --tw-ring-color: rgb(251 203 116 / var(--tw-ring-opacity));
+ --tw-ring-color: rgb(34 197 94 / var(--tw-ring-opacity));
+}
+
+.focus\:ring-primary-600:focus {
+ --tw-ring-opacity: 1;
+ --tw-ring-color: rgb(214 131 56 / var(--tw-ring-opacity));
}
.focus\:ring-offset-2:focus {
@@ -2127,11 +2022,6 @@ video {
border-color: rgb(55 65 81 / var(--tw-border-opacity));
}
-.dark\:border-gray-800:is(.dark *) {
- --tw-border-opacity: 1;
- border-color: rgb(31 41 55 / var(--tw-border-opacity));
-}
-
.dark\:bg-gray-600:is(.dark *) {
--tw-bg-opacity: 1;
background-color: rgb(75 85 99 / var(--tw-bg-opacity));
@@ -2385,11 +2275,6 @@ video {
--tw-ring-color: rgb(127 29 29 / var(--tw-ring-opacity));
}
-.dark\:focus\:ring-primary-900:focus:is(.dark *) {
- --tw-ring-opacity: 1;
- --tw-ring-color: rgb(123 74 30 / var(--tw-ring-opacity));
-}
-
@media (min-width: 640px) {
.sm\:col-span-3 {
grid-column: span 3 / span 3;
@@ -2430,19 +2315,14 @@ video {
line-height: 2rem;
}
- .sm\:text-sm {
- font-size: 0.875rem;
- line-height: 1.25rem;
- }
-
.sm\:text-4xl {
font-size: 2.25rem;
line-height: 2.5rem;
}
- .sm\:text-lg {
- font-size: 1.125rem;
- line-height: 1.75rem;
+ .sm\:text-sm {
+ font-size: 0.875rem;
+ line-height: 1.25rem;
}
.sm\:text-xl {
@@ -2460,11 +2340,6 @@ video {
}
@media (min-width: 768px) {
- .md\:my-12 {
- margin-top: 3rem;
- margin-bottom: 3rem;
- }
-
.md\:mb-0 {
margin-bottom: 0px;
}
@@ -2477,22 +2352,14 @@ video {
margin-right: 0px;
}
- .md\:mr-6 {
- margin-right: 1.5rem;
- }
-
- .md\:mr-3 {
- margin-right: 0.75rem;
- }
-
- .md\:mr-14 {
- margin-right: 3.5rem;
- }
-
.md\:mr-10 {
margin-right: 2.5rem;
}
+ .md\:mr-6 {
+ margin-right: 1.5rem;
+ }
+
.md\:inline {
display: inline;
}
@@ -2505,6 +2372,10 @@ video {
height: 100vh;
}
+ .md\:grid-cols-2 {
+ grid-template-columns: repeat(2, minmax(0, 1fr));
+ }
+
.md\:grid-cols-3 {
grid-template-columns: repeat(3, minmax(0, 1fr));
}
@@ -2513,10 +2384,6 @@ video {
grid-template-columns: repeat(4, minmax(0, 1fr));
}
- .md\:grid-cols-2 {
- grid-template-columns: repeat(2, minmax(0, 1fr));
- }
-
.md\:items-center {
align-items: center;
}
@@ -2525,44 +2392,16 @@ video {
justify-content: space-between;
}
- .md\:gap-6 {
- gap: 1.5rem;
- }
-
- .md\:gap-x-6 {
- -moz-column-gap: 1.5rem;
- column-gap: 1.5rem;
- }
-
.md\:space-x-2 > :not([hidden]) ~ :not([hidden]) {
--tw-space-x-reverse: 0;
margin-right: calc(0.5rem * var(--tw-space-x-reverse));
margin-left: calc(0.5rem * calc(1 - var(--tw-space-x-reverse)));
}
- .md\:space-y-0 > :not([hidden]) ~ :not([hidden]) {
- --tw-space-y-reverse: 0;
- margin-top: calc(0px * calc(1 - var(--tw-space-y-reverse)));
- margin-bottom: calc(0px * var(--tw-space-y-reverse));
- }
-
.md\:py-10 {
padding-top: 2.5rem;
padding-bottom: 2.5rem;
}
-
- .md\:pt-20 {
- padding-top: 5rem;
- }
-
- .md\:pt-32 {
- padding-top: 8rem;
- }
-
- .md\:text-base {
- font-size: 1rem;
- line-height: 1.5rem;
- }
}
@media (min-width: 1024px) {
@@ -2598,14 +2437,6 @@ video {
width: auto;
}
- .lg\:grid-cols-3 {
- grid-template-columns: repeat(3, minmax(0, 1fr));
- }
-
- .lg\:grid-cols-2 {
- grid-template-columns: repeat(2, minmax(0, 1fr));
- }
-
.lg\:flex-row {
flex-direction: row;
}
@@ -2665,10 +2496,6 @@ video {
margin-right: calc(2rem * var(--tw-space-x-reverse));
margin-left: calc(2rem * calc(1 - var(--tw-space-x-reverse)));
}
-
- .xl\:p-8 {
- padding: 2rem;
- }
}
@media (min-width: 1536px) {
diff --git a/src/AliasVault.Client/wwwroot/index.template.html b/src/AliasVault.Client/wwwroot/index.template.html
index f50be7eb6..5ab34962f 100644
--- a/src/AliasVault.Client/wwwroot/index.template.html
+++ b/src/AliasVault.Client/wwwroot/index.template.html
@@ -102,6 +102,7 @@
checkElapsedTime();
});
</script>
+ <script src="lib/qrcode.min.js?v=@CacheBuster"></script>
<script src="js/crypto.js?v=@CacheBuster"></script>
<script src="js/utilities.js?v=@CacheBuster"></script>
<script src="_framework/blazor.webassembly.js?v=@CacheBuster"></script>
diff --git a/src/AliasVault.Client/wwwroot/js/utilities.js b/src/AliasVault.Client/wwwroot/js/utilities.js
index db8ed8a01..42319cb2a 100644
--- a/src/AliasVault.Client/wwwroot/js/utilities.js
+++ b/src/AliasVault.Client/wwwroot/js/utilities.js
@@ -112,3 +112,45 @@ window.initTopMenu = function() {
initDarkModeSwitcher();
};
+/**
+ * Generate a QR code for the given id element that has a data-url attribute.
+ * @param id
+ */
+function generateQrCode(id) {
+ console.log(`Generating QR code for element with id "${id}".`);
+ // Find the element by id
+ const element = document.getElementById(id);
+
+ // Check if the element exists
+ if (!element) {
+ console.log(`Element with id "${id}" not found. QR code generation aborted.`);
+ return; // Silently fail
+ }
+
+ // Get the data-url attribute
+ const dataUrl = element.getAttribute('data-url');
+
+ // Check if data-url exists
+ if (!dataUrl) {
+ console.log(`No data-url attribute found on element with id "${id}". QR code generation aborted.`);
+ return; // Silently fail
+ }
+
+ // Create a container for the QR code
+ const qrContainer = document.createElement('div');
+ qrContainer.id = `qrcode-${id}`;
+ element.appendChild(qrContainer);
+
+ // Initialize QRCode object
+ let qrcode = new QRCode(qrContainer, {
+ width: 256,
+ height: 256,
+ colorDark : "#000000",
+ colorLight : "#ffffff",
+ correctLevel : QRCode.CorrectLevel.H
+ });
+
+ qrcode.makeCode(dataUrl);
+}
+
+
diff --git a/src/AliasVault.Client/wwwroot/lib/qrcode.min.js b/src/AliasVault.Client/wwwroot/lib/qrcode.min.js
new file mode 100644
index 000000000..993e88f39
--- /dev/null
+++ b/src/AliasVault.Client/wwwroot/lib/qrcode.min.js
@@ -0,0 +1 @@
+var QRCode;!function(){function a(a){this.mode=c.MODE_8BIT_BYTE,this.data=a,this.parsedData=[];for(var b=[],d=0,e=this.data.length;e>d;d++){var f=this.data.charCodeAt(d);f>65536?(b[0]=240|(1835008&f)>>>18,b[1]=128|(258048&f)>>>12,b[2]=128|(4032&f)>>>6,b[3]=128|63&f):f>2048?(b[0]=224|(61440&f)>>>12,b[1]=128|(4032&f)>>>6,b[2]=128|63&f):f>128?(b[0]=192|(1984&f)>>>6,b[1]=128|63&f):b[0]=f,this.parsedData=this.parsedData.concat(b)}this.parsedData.length!=this.data.length&&(this.parsedData.unshift(191),this.parsedData.unshift(187),this.parsedData.unshift(239))}function b(a,b){this.typeNumber=a,this.errorCorrectLevel=b,this.modules=null,this.moduleCount=0,this.dataCache=null,this.dataList=[]}function i(a,b){if(void 0==a.length)throw new Error(a.length+"/"+b);for(var c=0;c<a.length&&0==a[c];)c++;this.num=new Array(a.length-c+b);for(var d=0;d<a.length-c;d++)this.num[d]=a[d+c]}function j(a,b){this.totalCount=a,this.dataCount=b}function k(){this.buffer=[],this.length=0}function m(){return"undefined"!=typeof CanvasRenderingContext2D}function n(){var a=!1,b=navigator.userAgent;return/android/i.test(b)&&(a=!0,aMat=b.toString().match(/android ([0-9]\.[0-9])/i),aMat&&aMat[1]&&(a=parseFloat(aMat[1]))),a}function r(a,b){for(var c=1,e=s(a),f=0,g=l.length;g>=f;f++){var h=0;switch(b){case d.L:h=l[f][0];break;case d.M:h=l[f][1];break;case d.Q:h=l[f][2];break;case d.H:h=l[f][3]}if(h>=e)break;c++}if(c>l.length)throw new Error("Too long data");return c}function s(a){var b=encodeURI(a).toString().replace(/\%[0-9a-fA-F]{2}/g,"a");return b.length+(b.length!=a?3:0)}a.prototype={getLength:function(){return this.parsedData.length},write:function(a){for(var b=0,c=this.parsedData.length;c>b;b++)a.put(this.parsedData[b],8)}},b.prototype={addData:function(b){var c=new a(b);this.dataList.push(c),this.dataCache=null},isDark:function(a,b){if(0>a||this.moduleCount<=a||0>b||this.moduleCount<=b)throw new Error(a+","+b);return this.modules[a][b]},getModuleCount:function(){return this.moduleCount},make:function(){this.makeImpl(!1,this.getBestMaskPattern())},makeImpl:function(a,c){this.moduleCount=4*this.typeNumber+17,this.modules=new Array(this.moduleCount);for(var d=0;d<this.moduleCount;d++){this.modules[d]=new Array(this.moduleCount);for(var e=0;e<this.moduleCount;e++)this.modules[d][e]=null}this.setupPositionProbePattern(0,0),this.setupPositionProbePattern(this.moduleCount-7,0),this.setupPositionProbePattern(0,this.moduleCount-7),this.setupPositionAdjustPattern(),this.setupTimingPattern(),this.setupTypeInfo(a,c),this.typeNumber>=7&&this.setupTypeNumber(a),null==this.dataCache&&(this.dataCache=b.createData(this.typeNumber,this.errorCorrectLevel,this.dataList)),this.mapData(this.dataCache,c)},setupPositionProbePattern:function(a,b){for(var c=-1;7>=c;c++)if(!(-1>=a+c||this.moduleCount<=a+c))for(var d=-1;7>=d;d++)-1>=b+d||this.moduleCount<=b+d||(this.modules[a+c][b+d]=c>=0&&6>=c&&(0==d||6==d)||d>=0&&6>=d&&(0==c||6==c)||c>=2&&4>=c&&d>=2&&4>=d?!0:!1)},getBestMaskPattern:function(){for(var a=0,b=0,c=0;8>c;c++){this.makeImpl(!0,c);var d=f.getLostPoint(this);(0==c||a>d)&&(a=d,b=c)}return b},createMovieClip:function(a,b,c){var d=a.createEmptyMovieClip(b,c),e=1;this.make();for(var f=0;f<this.modules.length;f++)for(var g=f*e,h=0;h<this.modules[f].length;h++){var i=h*e,j=this.modules[f][h];j&&(d.beginFill(0,100),d.moveTo(i,g),d.lineTo(i+e,g),d.lineTo(i+e,g+e),d.lineTo(i,g+e),d.endFill())}return d},setupTimingPattern:function(){for(var a=8;a<this.moduleCount-8;a++)null==this.modules[a][6]&&(this.modules[a][6]=0==a%2);for(var b=8;b<this.moduleCount-8;b++)null==this.modules[6][b]&&(this.modules[6][b]=0==b%2)},setupPositionAdjustPattern:function(){for(var a=f.getPatternPosition(this.typeNumber),b=0;b<a.length;b++)for(var c=0;c<a.length;c++){var d=a[b],e=a[c];if(null==this.modules[d][e])for(var g=-2;2>=g;g++)for(var h=-2;2>=h;h++)this.modules[d+g][e+h]=-2==g||2==g||-2==h||2==h||0==g&&0==h?!0:!1}},setupTypeNumber:function(a){for(var b=f.getBCHTypeNumber(this.typeNumber),c=0;18>c;c++){var d=!a&&1==(1&b>>c);this.modules[Math.floor(c/3)][c%3+this.moduleCount-8-3]=d}for(var c=0;18>c;c++){var d=!a&&1==(1&b>>c);this.modules[c%3+this.moduleCount-8-3][Math.floor(c/3)]=d}},setupTypeInfo:function(a,b){for(var c=this.errorCorrectLevel<<3|b,d=f.getBCHTypeInfo(c),e=0;15>e;e++){var g=!a&&1==(1&d>>e);6>e?this.modules[e][8]=g:8>e?this.modules[e+1][8]=g:this.modules[this.moduleCount-15+e][8]=g}for(var e=0;15>e;e++){var g=!a&&1==(1&d>>e);8>e?this.modules[8][this.moduleCount-e-1]=g:9>e?this.modules[8][15-e-1+1]=g:this.modules[8][15-e-1]=g}this.modules[this.moduleCount-8][8]=!a},mapData:function(a,b){for(var c=-1,d=this.moduleCount-1,e=7,g=0,h=this.moduleCount-1;h>0;h-=2)for(6==h&&h--;;){for(var i=0;2>i;i++)if(null==this.modules[d][h-i]){var j=!1;g<a.length&&(j=1==(1&a[g]>>>e));var k=f.getMask(b,d,h-i);k&&(j=!j),this.modules[d][h-i]=j,e--,-1==e&&(g++,e=7)}if(d+=c,0>d||this.moduleCount<=d){d-=c,c=-c;break}}}},b.PAD0=236,b.PAD1=17,b.createData=function(a,c,d){for(var e=j.getRSBlocks(a,c),g=new k,h=0;h<d.length;h++){var i=d[h];g.put(i.mode,4),g.put(i.getLength(),f.getLengthInBits(i.mode,a)),i.write(g)}for(var l=0,h=0;h<e.length;h++)l+=e[h].dataCount;if(g.getLengthInBits()>8*l)throw new Error("code length overflow. ("+g.getLengthInBits()+">"+8*l+")");for(g.getLengthInBits()+4<=8*l&&g.put(0,4);0!=g.getLengthInBits()%8;)g.putBit(!1);for(;;){if(g.getLengthInBits()>=8*l)break;if(g.put(b.PAD0,8),g.getLengthInBits()>=8*l)break;g.put(b.PAD1,8)}return b.createBytes(g,e)},b.createBytes=function(a,b){for(var c=0,d=0,e=0,g=new Array(b.length),h=new Array(b.length),j=0;j<b.length;j++){var k=b[j].dataCount,l=b[j].totalCount-k;d=Math.max(d,k),e=Math.max(e,l),g[j]=new Array(k);for(var m=0;m<g[j].length;m++)g[j][m]=255&a.buffer[m+c];c+=k;var n=f.getErrorCorrectPolynomial(l),o=new i(g[j],n.getLength()-1),p=o.mod(n);h[j]=new Array(n.getLength()-1);for(var m=0;m<h[j].length;m++){var q=m+p.getLength()-h[j].length;h[j][m]=q>=0?p.get(q):0}}for(var r=0,m=0;m<b.length;m++)r+=b[m].totalCount;for(var s=new Array(r),t=0,m=0;d>m;m++)for(var j=0;j<b.length;j++)m<g[j].length&&(s[t++]=g[j][m]);for(var m=0;e>m;m++)for(var j=0;j<b.length;j++)m<h[j].length&&(s[t++]=h[j][m]);return s};for(var c={MODE_NUMBER:1,MODE_ALPHA_NUM:2,MODE_8BIT_BYTE:4,MODE_KANJI:8},d={L:1,M:0,Q:3,H:2},e={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7},f={PATTERN_POSITION_TABLE:[[],[6,18],[6,22],[6,26],[6,30],[6,34],[6,22,38],[6,24,42],[6,26,46],[6,28,50],[6,30,54],[6,32,58],[6,34,62],[6,26,46,66],[6,26,48,70],[6,26,50,74],[6,30,54,78],[6,30,56,82],[6,30,58,86],[6,34,62,90],[6,28,50,72,94],[6,26,50,74,98],[6,30,54,78,102],[6,28,54,80,106],[6,32,58,84,110],[6,30,58,86,114],[6,34,62,90,118],[6,26,50,74,98,122],[6,30,54,78,102,126],[6,26,52,78,104,130],[6,30,56,82,108,134],[6,34,60,86,112,138],[6,30,58,86,114,142],[6,34,62,90,118,146],[6,30,54,78,102,126,150],[6,24,50,76,102,128,154],[6,28,54,80,106,132,158],[6,32,58,84,110,136,162],[6,26,54,82,110,138,166],[6,30,58,86,114,142,170]],G15:1335,G18:7973,G15_MASK:21522,getBCHTypeInfo:function(a){for(var b=a<<10;f.getBCHDigit(b)-f.getBCHDigit(f.G15)>=0;)b^=f.G15<<f.getBCHDigit(b)-f.getBCHDigit(f.G15);return(a<<10|b)^f.G15_MASK},getBCHTypeNumber:function(a){for(var b=a<<12;f.getBCHDigit(b)-f.getBCHDigit(f.G18)>=0;)b^=f.G18<<f.getBCHDigit(b)-f.getBCHDigit(f.G18);return a<<12|b},getBCHDigit:function(a){for(var b=0;0!=a;)b++,a>>>=1;return b},getPatternPosition:function(a){return f.PATTERN_POSITION_TABLE[a-1]},getMask:function(a,b,c){switch(a){case e.PATTERN000:return 0==(b+c)%2;case e.PATTERN001:return 0==b%2;case e.PATTERN010:return 0==c%3;case e.PATTERN011:return 0==(b+c)%3;case e.PATTERN100:return 0==(Math.floor(b/2)+Math.floor(c/3))%2;case e.PATTERN101:return 0==b*c%2+b*c%3;case e.PATTERN110:return 0==(b*c%2+b*c%3)%2;case e.PATTERN111:return 0==(b*c%3+(b+c)%2)%2;default:throw new Error("bad maskPattern:"+a)}},getErrorCorrectPolynomial:function(a){for(var b=new i([1],0),c=0;a>c;c++)b=b.multiply(new i([1,g.gexp(c)],0));return b},getLengthInBits:function(a,b){if(b>=1&&10>b)switch(a){case c.MODE_NUMBER:return 10;case c.MODE_ALPHA_NUM:return 9;case c.MODE_8BIT_BYTE:return 8;case c.MODE_KANJI:return 8;default:throw new Error("mode:"+a)}else if(27>b)switch(a){case c.MODE_NUMBER:return 12;case c.MODE_ALPHA_NUM:return 11;case c.MODE_8BIT_BYTE:return 16;case c.MODE_KANJI:return 10;default:throw new Error("mode:"+a)}else{if(!(41>b))throw new Error("type:"+b);switch(a){case c.MODE_NUMBER:return 14;case c.MODE_ALPHA_NUM:return 13;case c.MODE_8BIT_BYTE:return 16;case c.MODE_KANJI:return 12;default:throw new Error("mode:"+a)}}},getLostPoint:function(a){for(var b=a.getModuleCount(),c=0,d=0;b>d;d++)for(var e=0;b>e;e++){for(var f=0,g=a.isDark(d,e),h=-1;1>=h;h++)if(!(0>d+h||d+h>=b))for(var i=-1;1>=i;i++)0>e+i||e+i>=b||(0!=h||0!=i)&&g==a.isDark(d+h,e+i)&&f++;f>5&&(c+=3+f-5)}for(var d=0;b-1>d;d++)for(var e=0;b-1>e;e++){var j=0;a.isDark(d,e)&&j++,a.isDark(d+1,e)&&j++,a.isDark(d,e+1)&&j++,a.isDark(d+1,e+1)&&j++,(0==j||4==j)&&(c+=3)}for(var d=0;b>d;d++)for(var e=0;b-6>e;e++)a.isDark(d,e)&&!a.isDark(d,e+1)&&a.isDark(d,e+2)&&a.isDark(d,e+3)&&a.isDark(d,e+4)&&!a.isDark(d,e+5)&&a.isDark(d,e+6)&&(c+=40);for(var e=0;b>e;e++)for(var d=0;b-6>d;d++)a.isDark(d,e)&&!a.isDark(d+1,e)&&a.isDark(d+2,e)&&a.isDark(d+3,e)&&a.isDark(d+4,e)&&!a.isDark(d+5,e)&&a.isDark(d+6,e)&&(c+=40);for(var k=0,e=0;b>e;e++)for(var d=0;b>d;d++)a.isDark(d,e)&&k++;var l=Math.abs(100*k/b/b-50)/5;return c+=10*l}},g={glog:function(a){if(1>a)throw new Error("glog("+a+")");return g.LOG_TABLE[a]},gexp:function(a){for(;0>a;)a+=255;for(;a>=256;)a-=255;return g.EXP_TABLE[a]},EXP_TABLE:new Array(256),LOG_TABLE:new Array(256)},h=0;8>h;h++)g.EXP_TABLE[h]=1<<h;for(var h=8;256>h;h++)g.EXP_TABLE[h]=g.EXP_TABLE[h-4]^g.EXP_TABLE[h-5]^g.EXP_TABLE[h-6]^g.EXP_TABLE[h-8];for(var h=0;255>h;h++)g.LOG_TABLE[g.EXP_TABLE[h]]=h;i.prototype={get:function(a){return this.num[a]},getLength:function(){return this.num.length},multiply:function(a){for(var b=new Array(this.getLength()+a.getLength()-1),c=0;c<this.getLength();c++)for(var d=0;d<a.getLength();d++)b[c+d]^=g.gexp(g.glog(this.get(c))+g.glog(a.get(d)));return new i(b,0)},mod:function(a){if(this.getLength()-a.getLength()<0)return this;for(var b=g.glog(this.get(0))-g.glog(a.get(0)),c=new Array(this.getLength()),d=0;d<this.getLength();d++)c[d]=this.get(d);for(var d=0;d<a.getLength();d++)c[d]^=g.gexp(g.glog(a.get(d))+b);return new i(c,0).mod(a)}},j.RS_BLOCK_TABLE=[[1,26,19],[1,26,16],[1,26,13],[1,26,9],[1,44,34],[1,44,28],[1,44,22],[1,44,16],[1,70,55],[1,70,44],[2,35,17],[2,35,13],[1,100,80],[2,50,32],[2,50,24],[4,25,9],[1,134,108],[2,67,43],[2,33,15,2,34,16],[2,33,11,2,34,12],[2,86,68],[4,43,27],[4,43,19],[4,43,15],[2,98,78],[4,49,31],[2,32,14,4,33,15],[4,39,13,1,40,14],[2,121,97],[2,60,38,2,61,39],[4,40,18,2,41,19],[4,40,14,2,41,15],[2,146,116],[3,58,36,2,59,37],[4,36,16,4,37,17],[4,36,12,4,37,13],[2,86,68,2,87,69],[4,69,43,1,70,44],[6,43,19,2,44,20],[6,43,15,2,44,16],[4,101,81],[1,80,50,4,81,51],[4,50,22,4,51,23],[3,36,12,8,37,13],[2,116,92,2,117,93],[6,58,36,2,59,37],[4,46,20,6,47,21],[7,42,14,4,43,15],[4,133,107],[8,59,37,1,60,38],[8,44,20,4,45,21],[12,33,11,4,34,12],[3,145,115,1,146,116],[4,64,40,5,65,41],[11,36,16,5,37,17],[11,36,12,5,37,13],[5,109,87,1,110,88],[5,65,41,5,66,42],[5,54,24,7,55,25],[11,36,12],[5,122,98,1,123,99],[7,73,45,3,74,46],[15,43,19,2,44,20],[3,45,15,13,46,16],[1,135,107,5,136,108],[10,74,46,1,75,47],[1,50,22,15,51,23],[2,42,14,17,43,15],[5,150,120,1,151,121],[9,69,43,4,70,44],[17,50,22,1,51,23],[2,42,14,19,43,15],[3,141,113,4,142,114],[3,70,44,11,71,45],[17,47,21,4,48,22],[9,39,13,16,40,14],[3,135,107,5,136,108],[3,67,41,13,68,42],[15,54,24,5,55,25],[15,43,15,10,44,16],[4,144,116,4,145,117],[17,68,42],[17,50,22,6,51,23],[19,46,16,6,47,17],[2,139,111,7,140,112],[17,74,46],[7,54,24,16,55,25],[34,37,13],[4,151,121,5,152,122],[4,75,47,14,76,48],[11,54,24,14,55,25],[16,45,15,14,46,16],[6,147,117,4,148,118],[6,73,45,14,74,46],[11,54,24,16,55,25],[30,46,16,2,47,17],[8,132,106,4,133,107],[8,75,47,13,76,48],[7,54,24,22,55,25],[22,45,15,13,46,16],[10,142,114,2,143,115],[19,74,46,4,75,47],[28,50,22,6,51,23],[33,46,16,4,47,17],[8,152,122,4,153,123],[22,73,45,3,74,46],[8,53,23,26,54,24],[12,45,15,28,46,16],[3,147,117,10,148,118],[3,73,45,23,74,46],[4,54,24,31,55,25],[11,45,15,31,46,16],[7,146,116,7,147,117],[21,73,45,7,74,46],[1,53,23,37,54,24],[19,45,15,26,46,16],[5,145,115,10,146,116],[19,75,47,10,76,48],[15,54,24,25,55,25],[23,45,15,25,46,16],[13,145,115,3,146,116],[2,74,46,29,75,47],[42,54,24,1,55,25],[23,45,15,28,46,16],[17,145,115],[10,74,46,23,75,47],[10,54,24,35,55,25],[19,45,15,35,46,16],[17,145,115,1,146,116],[14,74,46,21,75,47],[29,54,24,19,55,25],[11,45,15,46,46,16],[13,145,115,6,146,116],[14,74,46,23,75,47],[44,54,24,7,55,25],[59,46,16,1,47,17],[12,151,121,7,152,122],[12,75,47,26,76,48],[39,54,24,14,55,25],[22,45,15,41,46,16],[6,151,121,14,152,122],[6,75,47,34,76,48],[46,54,24,10,55,25],[2,45,15,64,46,16],[17,152,122,4,153,123],[29,74,46,14,75,47],[49,54,24,10,55,25],[24,45,15,46,46,16],[4,152,122,18,153,123],[13,74,46,32,75,47],[48,54,24,14,55,25],[42,45,15,32,46,16],[20,147,117,4,148,118],[40,75,47,7,76,48],[43,54,24,22,55,25],[10,45,15,67,46,16],[19,148,118,6,149,119],[18,75,47,31,76,48],[34,54,24,34,55,25],[20,45,15,61,46,16]],j.getRSBlocks=function(a,b){var c=j.getRsBlockTable(a,b);if(void 0==c)throw new Error("bad rs block @ typeNumber:"+a+"/errorCorrectLevel:"+b);for(var d=c.length/3,e=[],f=0;d>f;f++)for(var g=c[3*f+0],h=c[3*f+1],i=c[3*f+2],k=0;g>k;k++)e.push(new j(h,i));return e},j.getRsBlockTable=function(a,b){switch(b){case d.L:return j.RS_BLOCK_TABLE[4*(a-1)+0];case d.M:return j.RS_BLOCK_TABLE[4*(a-1)+1];case d.Q:return j.RS_BLOCK_TABLE[4*(a-1)+2];case d.H:return j.RS_BLOCK_TABLE[4*(a-1)+3];default:return void 0}},k.prototype={get:function(a){var b=Math.floor(a/8);return 1==(1&this.buffer[b]>>>7-a%8)},put:function(a,b){for(var c=0;b>c;c++)this.putBit(1==(1&a>>>b-c-1))},getLengthInBits:function(){return this.length},putBit:function(a){var b=Math.floor(this.length/8);this.buffer.length<=b&&this.buffer.push(0),a&&(this.buffer[b]|=128>>>this.length%8),this.length++}};var l=[[17,14,11,7],[32,26,20,14],[53,42,32,24],[78,62,46,34],[106,84,60,44],[134,106,74,58],[154,122,86,64],[192,152,108,84],[230,180,130,98],[271,213,151,119],[321,251,177,137],[367,287,203,155],[425,331,241,177],[458,362,258,194],[520,412,292,220],[586,450,322,250],[644,504,364,280],[718,560,394,310],[792,624,442,338],[858,666,482,382],[929,711,509,403],[1003,779,565,439],[1091,857,611,461],[1171,911,661,511],[1273,997,715,535],[1367,1059,751,593],[1465,1125,805,625],[1528,1190,868,658],[1628,1264,908,698],[1732,1370,982,742],[1840,1452,1030,790],[1952,1538,1112,842],[2068,1628,1168,898],[2188,1722,1228,958],[2303,1809,1283,983],[2431,1911,1351,1051],[2563,1989,1423,1093],[2699,2099,1499,1139],[2809,2213,1579,1219],[2953,2331,1663,1273]],o=function(){var a=function(a,b){this._el=a,this._htOption=b};return a.prototype.draw=function(a){function g(a,b){var c=document.createElementNS("http://www.w3.org/2000/svg",a);for(var d in b)b.hasOwnProperty(d)&&c.setAttribute(d,b[d]);return c}var b=this._htOption,c=this._el,d=a.getModuleCount();Math.floor(b.width/d),Math.floor(b.height/d),this.clear();var h=g("svg",{viewBox:"0 0 "+String(d)+" "+String(d),width:"100%",height:"100%",fill:b.colorLight});h.setAttributeNS("http://www.w3.org/2000/xmlns/","xmlns:xlink","http://www.w3.org/1999/xlink"),c.appendChild(h),h.appendChild(g("rect",{fill:b.colorDark,width:"1",height:"1",id:"template"}));for(var i=0;d>i;i++)for(var j=0;d>j;j++)if(a.isDark(i,j)){var k=g("use",{x:String(i),y:String(j)});k.setAttributeNS("http://www.w3.org/1999/xlink","href","#template"),h.appendChild(k)}},a.prototype.clear=function(){for(;this._el.hasChildNodes();)this._el.removeChild(this._el.lastChild)},a}(),p="svg"===document.documentElement.tagName.toLowerCase(),q=p?o:m()?function(){function a(){this._elImage.src=this._elCanvas.toDataURL("image/png"),this._elImage.style.display="block",this._elCanvas.style.display="none"}function d(a,b){var c=this;if(c._fFail=b,c._fSuccess=a,null===c._bSupportDataURI){var d=document.createElement("img"),e=function(){c._bSupportDataURI=!1,c._fFail&&_fFail.call(c)},f=function(){c._bSupportDataURI=!0,c._fSuccess&&c._fSuccess.call(c)};return d.onabort=e,d.onerror=e,d.onload=f,d.src="data:image/gif;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==",void 0}c._bSupportDataURI===!0&&c._fSuccess?c._fSuccess.call(c):c._bSupportDataURI===!1&&c._fFail&&c._fFail.call(c)}if(this._android&&this._android<=2.1){var b=1/window.devicePixelRatio,c=CanvasRenderingContext2D.prototype.drawImage;CanvasRenderingContext2D.prototype.drawImage=function(a,d,e,f,g,h,i,j){if("nodeName"in a&&/img/i.test(a.nodeName))for(var l=arguments.length-1;l>=1;l--)arguments[l]=arguments[l]*b;else"undefined"==typeof j&&(arguments[1]*=b,arguments[2]*=b,arguments[3]*=b,arguments[4]*=b);c.apply(this,arguments)}}var e=function(a,b){this._bIsPainted=!1,this._android=n(),this._htOption=b,this._elCanvas=document.createElement("canvas"),this._elCanvas.width=b.width,this._elCanvas.height=b.height,a.appendChild(this._elCanvas),this._el=a,this._oContext=this._elCanvas.getContext("2d"),this._bIsPainted=!1,this._elImage=document.createElement("img"),this._elImage.style.display="none",this._el.appendChild(this._elImage),this._bSupportDataURI=null};return e.prototype.draw=function(a){var b=this._elImage,c=this._oContext,d=this._htOption,e=a.getModuleCount(),f=d.width/e,g=d.height/e,h=Math.round(f),i=Math.round(g);b.style.display="none",this.clear();for(var j=0;e>j;j++)for(var k=0;e>k;k++){var l=a.isDark(j,k),m=k*f,n=j*g;c.strokeStyle=l?d.colorDark:d.colorLight,c.lineWidth=1,c.fillStyle=l?d.colorDark:d.colorLight,c.fillRect(m,n,f,g),c.strokeRect(Math.floor(m)+.5,Math.floor(n)+.5,h,i),c.strokeRect(Math.ceil(m)-.5,Math.ceil(n)-.5,h,i)}this._bIsPainted=!0},e.prototype.makeImage=function(){this._bIsPainted&&d.call(this,a)},e.prototype.isPainted=function(){return this._bIsPainted},e.prototype.clear=function(){this._oContext.clearRect(0,0,this._elCanvas.width,this._elCanvas.height),this._bIsPainted=!1},e.prototype.round=function(a){return a?Math.floor(1e3*a)/1e3:a},e}():function(){var a=function(a,b){this._el=a,this._htOption=b};return a.prototype.draw=function(a){for(var b=this._htOption,c=this._el,d=a.getModuleCount(),e=Math.floor(b.width/d),f=Math.floor(b.height/d),g=['<table style="border:0;border-collapse:collapse;">'],h=0;d>h;h++){g.push("<tr>");for(var i=0;d>i;i++)g.push('<td style="border:0;border-collapse:collapse;padding:0;margin:0;width:'+e+"px;height:"+f+"px;background-color:"+(a.isDark(h,i)?b.colorDark:b.colorLight)+';"></td>');g.push("</tr>")}g.push("</table>"),c.innerHTML=g.join("");var j=c.childNodes[0],k=(b.width-j.offsetWidth)/2,l=(b.height-j.offsetHeight)/2;k>0&&l>0&&(j.style.margin=l+"px "+k+"px")},a.prototype.clear=function(){this._el.innerHTML=""},a}();QRCode=function(a,b){if(this._htOption={width:256,height:256,typeNumber:4,colorDark:"#000000",colorLight:"#ffffff",correctLevel:d.H},"string"==typeof b&&(b={text:b}),b)for(var c in b)this._htOption[c]=b[c];"string"==typeof a&&(a=document.getElementById(a)),this._android=n(),this._el=a,this._oQRCode=null,this._oDrawing=new q(this._el,this._htOption),this._htOption.text&&this.makeCode(this._htOption.text)},QRCode.prototype.makeCode=function(a){this._oQRCode=new b(r(a,this._htOption.correctLevel),this._htOption.correctLevel),this._oQRCode.addData(a),this._oQRCode.make(),this._el.title=a,this._oDrawing.draw(this._oQRCode),this.makeImage()},QRCode.prototype.makeImage=function(){"function"==typeof this._oDrawing.makeImage&&(!this._android||this._android>=3)&&this._oDrawing.makeImage()},QRCode.prototype.clear=function(){this._oDrawing.clear()},QRCode.CorrectLevel=d}();
\ No newline at end of file
diff --git a/src/AliasVault.Shared/Models/LoginModel2Fa.cs b/src/AliasVault.Shared/Models/LoginModel2Fa.cs
new file mode 100644
index 000000000..54d00ec37
--- /dev/null
+++ b/src/AliasVault.Shared/Models/LoginModel2Fa.cs
@@ -0,0 +1,27 @@
+//-----------------------------------------------------------------------
+// <copyright file="LoginModel2Fa.cs" company="lanedirt">
+// Copyright (c) lanedirt. All rights reserved.
+// Licensed under the MIT license. See LICENSE.md file in the project root for full license information.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace AliasVault.Shared.Models;
+
+using System.ComponentModel.DataAnnotations;
+
+/// <summary>
+/// Login model for two factor authentication step.
+/// </summary>
+public class LoginModel2Fa
+{
+ /// <summary>
+ /// Gets or sets the two factor code.
+ /// </summary>
+ [Required]
+ public string TwoFactorCode { get; set; } = null!;
+
+ /// <summary>
+ /// Gets or sets a value indicating whether the current machine should not be asked for 2FA the next time.
+ /// </summary>
+ public bool RememberMachine { get; set; }
+}
diff --git a/src/AliasVault.Shared/Models/WebApi/Auth/ValidateLoginRequest2Fa.cs b/src/AliasVault.Shared/Models/WebApi/Auth/ValidateLoginRequest2Fa.cs
new file mode 100644
index 000000000..e272e5fa2
--- /dev/null
+++ b/src/AliasVault.Shared/Models/WebApi/Auth/ValidateLoginRequest2Fa.cs
@@ -0,0 +1,33 @@
+//-----------------------------------------------------------------------
+// <copyright file="ValidateLoginRequest2Fa.cs" company="lanedirt">
+// Copyright (c) lanedirt. All rights reserved.
+// Licensed under the MIT license. See LICENSE.md file in the project root for full license information.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace AliasVault.Shared.Models.WebApi.Auth
+{
+ /// <summary>
+ /// Represents a request to validate a login with added 2-factor authentication code.
+ /// </summary>
+ public class ValidateLoginRequest2Fa : ValidateLoginRequest
+ {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="ValidateLoginRequest2Fa"/> class.
+ /// </summary>
+ /// <param name="username">Username.</param>
+ /// <param name="clientPublicEphemeral">Client public ephemeral.</param>
+ /// <param name="clientSessionProof">Client session proof.</param>
+ /// <param name="code2Fa">2-factor authentication code.</param>
+ public ValidateLoginRequest2Fa(string username, string clientPublicEphemeral, string clientSessionProof, string code2Fa)
+ : base(username, clientPublicEphemeral, clientSessionProof)
+ {
+ Code2Fa = code2Fa;
+ }
+
+ /// <summary>
+ /// Gets the 2-factor authentication code.
+ /// </summary>
+ public string Code2Fa { get; }
+ }
+}
diff --git a/src/AliasVault.Shared/Models/WebApi/Auth/ValidateLoginResponse.cs b/src/AliasVault.Shared/Models/WebApi/Auth/ValidateLoginResponse.cs
index b9e66e4f5..58d16d859 100644
--- a/src/AliasVault.Shared/Models/WebApi/Auth/ValidateLoginResponse.cs
+++ b/src/AliasVault.Shared/Models/WebApi/Auth/ValidateLoginResponse.cs
@@ -17,14 +17,22 @@ public class ValidateLoginResponse
/// <summary>
/// Initializes a new instance of the <see cref="ValidateLoginResponse"/> class.
/// </summary>
+ /// <param name="requiresTwoFactor">Whether two factor authentication is required to login the user.</param>
/// <param name="serverSessionProof">Client session proof.</param>
/// <param name="token">Token model.</param>
- public ValidateLoginResponse(string serverSessionProof, TokenModel token)
+ public ValidateLoginResponse(bool requiresTwoFactor, string serverSessionProof, TokenModel? token)
{
+ RequiresTwoFactor = requiresTwoFactor;
ServerSessionProof = serverSessionProof;
Token = token;
}
+ /// <summary>
+ /// Gets or sets a value indicating whether two factor authentication is required to finish login.
+ /// </summary>
+ [JsonPropertyName("requiresTwoFactor")]
+ public bool RequiresTwoFactor { get; set; }
+
/// <summary>
/// Gets or sets the server's session proof.
/// </summary>
@@ -35,5 +43,5 @@ public class ValidateLoginResponse
/// Gets or sets the JWT and refresh token.
/// </summary>
[JsonPropertyName("token")]
- public TokenModel Token { get; set; }
+ public TokenModel? Token { get; set; }
}