Privacy-first password manager with built-in email aliasing. Fully encrypted and self-hostable.
Remove broken mobile unlock scaffolding from AliasVault.Client as its now deprecated (#2159)
Leendert de Borst05bc4506ad93
diff --git a/apps/server/AliasVault.Client/Auth/Components/MobileUnlockModal.razor b/apps/server/AliasVault.Client/Auth/Components/MobileUnlockModal.razordeleted file mode 100644index 832dc2990..000000000--- a/apps/server/AliasVault.Client/Auth/Components/MobileUnlockModal.razor+++ /dev/null@@ -1,320 +0,0 @@-@using AliasVault.Client.Auth.Models-@using AliasVault.Client.Auth.Services-@using AliasVault.Client.Main.Components.Layout-@using AliasVault.Client.Utilities-@using Microsoft.Extensions.Localization-@using Microsoft.Extensions.DependencyInjection-@implements IDisposable--@if (IsOpen)-{- <ModalWrapper>- <!-- Backdrop -->- <div class="fixed inset-0 bg-black bg-opacity-80 transition-opacity" @onclick="HandleClose"></div>-- <!-- Modal -->- <div class="relative transform overflow-hidden rounded-lg bg-white dark:bg-gray-800 px-6 pb-6 pt-5 text-left shadow-xl transition-all w-full max-w-md mx-4">- <!-- Close button -->- <button type="button" class="absolute right-4 top-4 text-gray-400 hover:text-gray-500 focus:outline-none" @onclick="HandleClose">- <span class="sr-only">@SharedLocalizer["Close"]</span>- <svg class="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor">- <path stroke-linecap="round" stroke-linejoin="round" d="M6 18L18 6M6 6l12 12" />- </svg>- </button>-- <!-- Content -->- <div class="mt-3">- <h3 class="text-xl font-bold text-gray-900 dark:text-white mb-2">- @Title- </h3>- <p class="text-sm text-gray-600 dark:text-gray-400 mb-4">- @Description- </p>-- @if (!string.IsNullOrEmpty(_errorMessage))- {- <div class="mb-4 p-3 bg-red-100 dark:bg-red-900/30 border border-red-400 dark:border-red-700 rounded text-red-700 dark:text-red-400 text-sm">- @_errorMessage- </div>- }-- @if (!string.IsNullOrEmpty(_qrCodeUrl))- {- <div class="flex flex-col items-center mb-4">- <div id="@_qrElementId" data-url="@_qrCodeUrl" class="@(_isLoading ? "hidden" : "") mb-3 bg-white rounded-lg border-4 border-gray-200 dark:border-gray-600">- <!-- QR code will be rendered here -->- </div>- @if (!_isLoading)- {- <div class="text-gray-700 dark:text-gray-300 text-sm font-medium">- @FormatTime(_timeRemaining)- </div>- }- </div>- }-- @if (_isLoading && string.IsNullOrEmpty(_errorMessage))- {- <div class="flex justify-center py-8">- <div class="animate-spin rounded-full h-12 w-12 border-b-2 border-primary-600"></div>- </div>- }-- <button type="button" @onclick="HandleClose" class="mt-4 w-full inline-flex justify-center rounded-md bg-white dark:bg-gray-700 px-3 py-2 text-sm font-semibold text-gray-900 dark:text-gray-200 shadow-sm ring-1 ring-inset ring-gray-300 dark:ring-gray-600 hover:bg-gray-50 dark:hover:bg-gray-600 focus:outline-none focus:ring-2 focus:ring-primary-500">- @SharedLocalizer["Cancel"]- </button>- </div>- </div>- </ModalWrapper>-}--@code {- private string? _qrCodeUrl;- private MobileLoginErrorCode? _errorCode;- private string? _errorMessage;- private int _timeRemaining = 120; // 2 minutes in seconds- private MobileLoginUtility? _mobileLoginUtility;- private bool _isLoading = true;- private System.Threading.Timer? _countdownTimer;- private string _qrElementId = $"mobile-unlock-qr-{Guid.NewGuid():N}";-- [Inject]- private HttpClient Http { get; set; } = default!;-- [Inject]- private JsInteropService JsInteropService { get; set; } = default!;-- [Inject]- private ILogger<MobileUnlockModal> Logger { get; set; } = default!;-- [Inject]- private IStringLocalizerFactory LocalizerFactory { get; set; } = default!;-- [Inject]- private IServiceProvider ScopedServices { get; set; } = default!;-- private IStringLocalizer SharedLocalizer => LocalizerFactory.Create("SharedResources", "AliasVault.Client");-- private IStringLocalizer MobileLoginLocalizer => LocalizerFactory.Create("MobileLogin", "AliasVault.Client");-- /// <summary>- /// Whether the modal is open.- /// </summary>- [Parameter]- public bool IsOpen { get; set; }-- /// <summary>- /// Callback when the modal is closed.- /// </summary>- [Parameter]- public EventCallback OnClose { get; set; }-- /// <summary>- /// Callback when mobile login/unlock succeeds with the result.- /// </summary>- [Parameter]- public EventCallback<MobileLoginResult> OnSuccess { get; set; }-- /// <summary>- /// Mode - 'login' or 'unlock'.- /// </summary>- [Parameter]- public string Mode { get; set; } = "login";-- /// <summary>- /// Modal title based on mode.- /// </summary>- private string Title => Mode == "unlock"- ? LocalizerFactory.Create("Pages.Auth.MobileUnlockModal", "AliasVault.Client")["UnlockTitle"]- : LocalizerFactory.Create("Pages.Auth.MobileUnlockModal", "AliasVault.Client")["PageTitle"];-- /// <summary>- /// Modal description based on mode.- /// </summary>- private string Description => LocalizerFactory.Create("Pages.Auth.MobileUnlockModal", "AliasVault.Client")["ScanQrCodeDescription"];-- /// <inheritdoc />- protected override async Task OnParametersSetAsync()- {- await base.OnParametersSetAsync();-- if (IsOpen && _mobileLoginUtility == null)- {- await InitiateMobileLoginAsync();- }- else if (!IsOpen)- {- Cleanup();- }- }-- /// <summary>- /// Initialize mobile login when modal opens.- /// </summary>- private async Task InitiateMobileLoginAsync()- {- try- {- _isLoading = true;- _errorCode = null;- _errorMessage = null;- _qrCodeUrl = null;- _timeRemaining = 120;- StateHasChanged();-- // Initialize mobile login utility- var utilityLogger = ScopedServices.GetRequiredService<ILogger<MobileLoginUtility>>();- _mobileLoginUtility = new MobileLoginUtility(Http, JsInteropService, utilityLogger);-- // Initiate mobile login and get QR code data- var (requestId, publicKeyHash) = await _mobileLoginUtility.InitiateAsync();-- // Generate QR code with AliasVault prefix for mobile login- // Include public key hash as query parameter for security verification- _qrCodeUrl = $"aliasvault://open/mobile-unlock/{requestId}?pk={publicKeyHash}";-- // Render QR code while showing loading- StateHasChanged();- await Task.Delay(100); // Give DOM time to render- await JsInteropService.GenerateQrCode(_qrElementId);-- // Wait for QR code to be fully rendered before hiding loading- await Task.Delay(300);-- _isLoading = false;- StateHasChanged();-- // Start countdown timer- StartCountdownTimer();-- // Start polling for response- await _mobileLoginUtility.StartPollingAsync(- HandleSuccessAsync,- HandleErrorAsync);- }- catch (MobileLoginException ex)- {- Logger.LogError(ex, "Error initiating mobile login");- _isLoading = false;- _errorCode = ex.ErrorCode;- _errorMessage = GetErrorMessage(ex.ErrorCode);- StateHasChanged();- }- catch (Exception ex)- {- Logger.LogError(ex, "Error initiating mobile login");- _isLoading = false;- _errorCode = MobileLoginErrorCode.Generic;- _errorMessage = GetErrorMessage(MobileLoginErrorCode.Generic);- StateHasChanged();- }- }-- /// <summary>- /// Handle successful mobile login/unlock.- /// </summary>- private async Task HandleSuccessAsync(MobileLoginResult result)- {- try- {- // Call parent success callback- await OnSuccess.InvokeAsync(result);-- // Close modal after successful processing- await HandleClose();- }- catch (Exception ex)- {- Logger.LogError(ex, "Error handling mobile login success");- _errorMessage = SharedLocalizer["ErrorUnknown"];- StateHasChanged();- }- }-- /// <summary>- /// Handle error.- /// </summary>- private void HandleErrorAsync(MobileLoginErrorCode errorCode)- {- _isLoading = false;- _qrCodeUrl = null; // Hide QR code when error occurs- _errorCode = errorCode;- _errorMessage = GetErrorMessage(errorCode);- StateHasChanged();- }-- /// <summary>- /// Get translated error message for error code.- /// </summary>- private string GetErrorMessage(MobileLoginErrorCode errorCode)- {- return errorCode switch- {- MobileLoginErrorCode.Timeout => MobileLoginLocalizer["ErrorTimeout"],- MobileLoginErrorCode.Generic => SharedLocalizer["ErrorUnknown"],- _ => SharedLocalizer["ErrorUnknown"]- };- }-- /// <summary>- /// Handle modal close.- /// </summary>- private async Task HandleClose()- {- Cleanup();- await OnClose.InvokeAsync();- }-- /// <summary>- /// Cleanup resources.- /// </summary>- private void Cleanup()- {- _mobileLoginUtility?.Cleanup();- _mobileLoginUtility?.Dispose();- _mobileLoginUtility = null;- _countdownTimer?.Dispose();- _countdownTimer = null;- _qrCodeUrl = null;- _errorCode = null;- _errorMessage = null;- _timeRemaining = 120;- _isLoading = true;- }-- /// <summary>- /// Format time remaining as MM:SS.- /// </summary>- private string FormatTime(int seconds)- {- var mins = seconds / 60;- var secs = seconds % 60;- return $"{mins}:{secs:D2}";- }-- /// <summary>- /// Start countdown timer.- /// </summary>- private void StartCountdownTimer()- {- _countdownTimer = new System.Threading.Timer(_ =>- {- if (_timeRemaining > 0)- {- _timeRemaining--;- InvokeAsync(StateHasChanged);- }- else- {- _countdownTimer?.Dispose();- _mobileLoginUtility?.StopPolling();- }- }, null, TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(1));- }-- /// <inheritdoc />- public void Dispose()- {- Cleanup();- }-}diff --git a/apps/server/AliasVault.Client/Auth/Models/MobileLoginResult.cs b/apps/server/AliasVault.Client/Auth/Models/MobileLoginResult.csdeleted file mode 100644index bd11e42ea..000000000--- a/apps/server/AliasVault.Client/Auth/Models/MobileLoginResult.cs+++ /dev/null@@ -1,34 +0,0 @@-//------------------------------------------------------------------------// <copyright file="MobileLoginResult.cs" company="aliasvault">-// Copyright (c) aliasvault. All rights reserved.-// Licensed under the AGPLv3 license. See LICENSE.md file in the project root for full license information.-// </copyright>-//-------------------------------------------------------------------------namespace AliasVault.Client.Auth.Models;--/// <summary>-/// Result of a successful mobile login containing decrypted authentication data.-/// </summary>-public sealed class MobileLoginResult-{- /// <summary>- /// Gets or sets the username.- /// </summary>- public required string Username { get; set; }-- /// <summary>- /// Gets or sets the JWT access token.- /// </summary>- public required string Token { get; set; }-- /// <summary>- /// Gets or sets the refresh token.- /// </summary>- public required string RefreshToken { get; set; }-- /// <summary>- /// Gets or sets the vault decryption key (base64 encoded).- /// </summary>- public required string DecryptionKey { get; set; }-}diff --git a/apps/server/AliasVault.Client/Auth/Pages/Login.razor b/apps/server/AliasVault.Client/Auth/Pages/Login.razorindex ad4f9a968..648bf6368 100644--- a/apps/server/AliasVault.Client/Auth/Pages/Login.razor+++ b/apps/server/AliasVault.Client/Auth/Pages/Login.razor@@ -121,12 +121,6 @@ else<button type="submit" id="login-button" class="w-full px-5 py-2 text-base font-medium text-center text-white bg-primary-700 rounded-lg hover:bg-primary-800 focus:ring-4 focus:ring-primary-300 dark:bg-primary-600 dark:hover:bg-primary-700 dark:focus:ring-primary-800 flex items-center justify-center gap-2">@Localizer["LoginButton"]</button>- <button type="button" id="mobile-login-button" @onclick="() => _showMobileLoginModal = true" class="hidden md:flex w-full px-5 py-2 text-base font-medium text-center text-gray-700 bg-white border border-gray-300 rounded-lg hover:bg-gray-100 focus:ring-4 focus:ring-gray-200 dark:bg-gray-700 dark:text-white dark:border-gray-600 dark:hover:bg-gray-600 dark:focus:ring-gray-700 items-center justify-center gap-2">- <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">- <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 18h.01M8 21h8a2 2 0 002-2V5a2 2 0 00-2-2H8a2 2 0 00-2 2v14a2 2 0 002 2z"></path>- </svg>- @Localizer["MobileDeviceLink"]- </button></div>@@ -141,11 +135,6 @@ else<FooterLogin />-<MobileUnlockModal IsOpen="@_showMobileLoginModal"- OnClose="() => _showMobileLoginModal = false"- OnSuccess="HandleMobileLoginSuccess"- Mode="login" />-@code {private readonly LoginFormModel _loginModel = new();private readonly LoginModel2Fa _loginModel2Fa = new();@@ -154,7 +143,6 @@ elseprivate ServerValidationErrors _serverValidationErrors = new();private bool _showTwoFactorAuthStep;private bool _showLoginWithRecoveryCodeStep;- private bool _showMobileLoginModal;private IStringLocalizer Localizer => LocalizerFactory.Create("Components.Auth.Login", "AliasVault.Client");private IStringLocalizer ApiErrorLocalizer => LocalizerFactory.Create("ApiErrors", "AliasVault.Client");@@ -467,61 +455,4 @@ elsereturn [];}- /// <summary>- /// Handle successful mobile login.- /// </summary>- private async Task HandleMobileLoginSuccess(MobileLoginResult result)- {- _loadingIndicator.Show(Localizer["LoggingInMessage"]);- _serverValidationErrors.Clear();-- try- {- // Clear global messages- GlobalNotificationService.ClearMessages();-- // Store the tokens in local storage.- await AuthService.StoreAccessTokenAsync(result.Token);- await AuthService.StoreRefreshTokenAsync(result.RefreshToken);- AuthService.StoreUsername(result.Username);-- // TODO: the mobile app is still v1-only, so it sends the vault encryption key of a legacy account directly.- // Resolve the full key chain here (KEK to AK to VEK plus the account private key) once the mobile app is- // migrated to the manifest-v1 structure and sends its KEK instead.- await AuthService.StoreSessionKeysAsync(Convert.FromBase64String(result.DecryptionKey), null);-- await AuthStateProvider.GetAuthenticationStateAsync();- GlobalNotificationService.ClearMessages();-- // Redirect to the page the user was trying to access before if set- var localStorageReturnUrl = await LocalStorage.GetItemAsync<string>(StorageKeys.ReturnUrl);- if (!string.IsNullOrEmpty(localStorageReturnUrl))- {- await LocalStorage.RemoveItemAsync(StorageKeys.ReturnUrl);- NavigationManager.NavigateTo(localStorageReturnUrl);- }- else- {- NavigationManager.NavigateTo("/");- }- }-#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(Localizer["LoginErrorMessage"]);- }-#endif- finally- {- _loadingIndicator.Hide();- }- }-}diff --git a/apps/server/AliasVault.Client/Auth/Pages/Unlock.razor b/apps/server/AliasVault.Client/Auth/Pages/Unlock.razorindex d5415b778..83af4fa13 100644--- a/apps/server/AliasVault.Client/Auth/Pages/Unlock.razor+++ b/apps/server/AliasVault.Client/Auth/Pages/Unlock.razor@@ -80,13 +80,6 @@ else@Localizer["UnlockButton"]</button></EditForm>-- <button type="button" id="mobile-unlock-button" @onclick="() => _showMobileUnlockModal = true" class="hidden md:flex w-full px-5 py-2 text-base font-medium text-center text-gray-700 bg-white border border-gray-300 rounded-lg hover:bg-gray-100 focus:ring-4 focus:ring-gray-200 dark:bg-gray-700 dark:text-white dark:border-gray-600 dark:hover:bg-gray-600 dark:focus:ring-gray-700 items-center justify-center gap-2 mt-4">- <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">- <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 18h.01M8 21h8a2 2 0 002-2V5a2 2 0 00-2-2H8a2 2 0 00-2 2v14a2 2 0 002 2z"></path>- </svg>- @Localizer["UnlockWithMobileButton"]- </button>}<div class="text-sm text-center font-medium text-gray-500 dark:text-gray-400 mt-6">@@ -96,11 +89,6 @@ else<FooterLogin />-<MobileUnlockModal IsOpen="@_showMobileUnlockModal"- OnClose="() => _showMobileUnlockModal = false"- OnSuccess="HandleMobileUnlockSuccess"- Mode="unlock" />-@code {/// <summary>/// Skip automatic WebAuthn unlock during page load if set to true.@@ -113,7 +101,6 @@ elseprivate bool IsWebAuthnLoading { get; set; }private bool ShowWebAuthnButton { get; set; }private bool IsPasswordFocused { get; set; }- private bool _showMobileUnlockModal;private readonly UnlockModel _unlockModel = new();private FullScreenLoadingIndicator _loadingIndicator = new();private ServerValidationErrors _serverValidationErrors = new();@@ -340,61 +327,4 @@ else}}- /// <summary>- /// Handle successful mobile unlock.- /// </summary>- private async Task HandleMobileUnlockSuccess(MobileLoginResult result)- {- _loadingIndicator.Show(Localizer["UnlockingVaultMessage"]);- _serverValidationErrors.Clear();-- try- {- await StatusCheck();-- // Revoke only the current specific token before setting new ones.- await AuthService.RevokeCurrentTokenAsync();-- // Store the new tokens.- await AuthService.StoreAccessTokenAsync(result.Token);- await AuthService.StoreRefreshTokenAsync(result.RefreshToken);- AuthService.StoreUsername(result.Username);-- // TODO: the mobile app is still v1-only, so it sends the vault encryption key of a legacy account directly.- // Resolve the full key chain here (KEK to AK to VEK plus the account private key) once the mobile app is- // migrated to the manifest-v1 structure and sends its KEK instead.- await AuthService.StoreSessionKeysAsync(Convert.FromBase64String(result.DecryptionKey), null);-- await AuthStateProvider.GetAuthenticationStateAsync();-- // Redirect to the page the user was trying to access before if set- var localStorageReturnUrl = await LocalStorage.GetItemAsync<string>(StorageKeys.ReturnUrl);- if (!string.IsNullOrEmpty(localStorageReturnUrl))- {- await LocalStorage.RemoveItemAsync(StorageKeys.ReturnUrl);- NavigationManager.NavigateTo(localStorageReturnUrl);- }- else- {- NavigationManager.NavigateTo("/");- }- }-#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(Localizer["GenericUnlockError"]);- }-#endif- finally- {- _loadingIndicator.Hide();- }- }}diff --git a/apps/server/AliasVault.Client/Auth/Services/MobileLoginUtility.cs b/apps/server/AliasVault.Client/Auth/Services/MobileLoginUtility.csdeleted file mode 100644index f0804bc6e..000000000--- a/apps/server/AliasVault.Client/Auth/Services/MobileLoginUtility.cs+++ /dev/null@@ -1,243 +0,0 @@-//------------------------------------------------------------------------// <copyright file="MobileLoginUtility.cs" company="aliasvault">-// Copyright (c) aliasvault. All rights reserved.-// Licensed under the AGPLv3 license. See LICENSE.md file in the project root for full license information.-// </copyright>-//-------------------------------------------------------------------------namespace AliasVault.Client.Auth.Services;--using System.Net.Http.Json;-using System.Security.Cryptography;-using System.Text;-using System.Text.Json;-using System.Threading;-using System.Threading.Tasks;-using AliasVault.Client.Auth.Models;-using AliasVault.Client.Services.JsInterop;-using AliasVault.Client.Utilities;-using AliasVault.Shared.Models.WebApi.V1.Auth;-using Microsoft.Extensions.Logging;--/// <summary>-/// Utility class for logging in with mobile app functionality.-/// </summary>-public sealed class MobileLoginUtility : IDisposable-{- private readonly HttpClient _httpClient;- private readonly JsInteropService _jsInteropService;- private readonly ILogger<MobileLoginUtility> _logger;-- private Timer? _pollingTimer;- private string? _requestId;- private string? _privateKey;- private string? _publicKeyHash;- private CancellationTokenSource? _cancellationTokenSource;-- /// <summary>- /// Initializes a new instance of the <see cref="MobileLoginUtility"/> class.- /// </summary>- /// <param name="httpClient">The HTTP client.</param>- /// <param name="jsInteropService">The JS interop service.</param>- /// <param name="logger">The logger.</param>- public MobileLoginUtility(HttpClient httpClient, JsInteropService jsInteropService, ILogger<MobileLoginUtility> logger)- {- _httpClient = httpClient;- _jsInteropService = jsInteropService;- _logger = logger;- }-- /// <summary>- /// Initiates a mobile login request and returns the request ID and public key hash for QR code generation.- /// </summary>- /// <returns>Tuple containing the request ID and public key hash.</returns>- /// <exception cref="MobileLoginException">Thrown when the request fails.</exception>- public async Task<(string RequestId, string PublicKeyHash)> InitiateAsync()- {- try- {- // Generate RSA key pair- var keyPair = await _jsInteropService.GenerateRsaKeyPair();- _privateKey = keyPair.PrivateKey;-- // Compute hash of public key for QR code binding- // This allows mobile app to verify the public key hasn't been swapped by the server- _publicKeyHash = ComputePublicKeyHash(keyPair.PublicKey);-- // Send public key to server- var request = new MobileLoginInitiateRequest- {- ClientPublicKey = keyPair.PublicKey,- };- var response = await _httpClient.PostAsJsonAsync(ApiRoute("Auth/mobile-login/initiate"), request);-- if (!response.IsSuccessStatusCode)- {- throw new MobileLoginException(MobileLoginErrorCode.Generic);- }-- var result = await response.Content.ReadFromJsonAsync<MobileLoginInitiateResponse>();- if (result == null)- {- throw new MobileLoginException(MobileLoginErrorCode.Generic);- }-- _requestId = result.RequestId;- return (_requestId, _publicKeyHash);- }- catch (MobileLoginException)- {- throw;- }- catch (Exception ex)- {- _logger.LogError(ex, "Failed to initiate mobile login");- throw new MobileLoginException(MobileLoginErrorCode.Generic);- }- }-- /// <summary>- /// Starts polling the server for mobile login response.- /// </summary>- /// <param name="onSuccess">Callback for successful authentication with decrypted login result.</param>- /// <param name="onError">Callback for errors with error code.</param>- /// <returns>Task.</returns>- public Task StartPollingAsync(Func<MobileLoginResult, Task> onSuccess, Action<MobileLoginErrorCode> onError)- {- if (string.IsNullOrEmpty(_requestId) || string.IsNullOrEmpty(_privateKey))- {- throw new InvalidOperationException("Must call InitiateAsync() before starting polling");- }-- _cancellationTokenSource = new CancellationTokenSource();-- // Start polling timer (every 3 seconds)- _pollingTimer = new Timer(async _ => await PollServerAsync(onSuccess, onError), null, TimeSpan.Zero, TimeSpan.FromSeconds(3));-- // Auto-stop after 3.5 minutes (adds 1 minute buffer to default 2 minute timer for edge cases)- Task.Delay(TimeSpan.FromSeconds(210), _cancellationTokenSource.Token)- .ContinueWith(- _ =>- {- if (!_cancellationTokenSource.IsCancellationRequested)- {- StopPolling();- onError(MobileLoginErrorCode.Timeout);- }- },- TaskScheduler.Default);-- return Task.CompletedTask;- }-- /// <summary>- /// Stops polling the server.- /// </summary>- public void StopPolling()- {- _pollingTimer?.Dispose();- _pollingTimer = null;- _cancellationTokenSource?.Cancel();- _cancellationTokenSource?.Dispose();- _cancellationTokenSource = null;- }-- /// <summary>- /// Cleans up resources.- /// </summary>- public void Cleanup()- {- StopPolling();- _privateKey = null;- _requestId = null;- _publicKeyHash = null;- }-- /// <inheritdoc/>- public void Dispose()- {- Cleanup();- }-- /// <summary>- /// Computes a SHA-256 hash of the public key and returns the first 16 characters.- /// </summary>- /// <param name="publicKey">The public key to hash.</param>- /// <returns>First 16 characters of the hex-encoded SHA-256 hash.</returns>- private static string ComputePublicKeyHash(string publicKey)- {- var bytes = Encoding.UTF8.GetBytes(publicKey);- var hashBytes = SHA256.HashData(bytes);- var hashHex = Convert.ToHexString(hashBytes).ToLowerInvariant();-- // Return first 16 characters for a compact but secure fingerprint- return hashHex[..16];- }-- private async Task PollServerAsync(Func<MobileLoginResult, Task> onSuccess, Action<MobileLoginErrorCode> onError)- {- if (string.IsNullOrEmpty(_requestId) || _cancellationTokenSource?.IsCancellationRequested == true)- {- return;- }-- try- {- var response = await _httpClient.GetAsync(ApiRoute($"Auth/mobile-login/poll/{_requestId}"));-- if (!response.IsSuccessStatusCode)- {- if (response.StatusCode == System.Net.HttpStatusCode.NotFound)- {- StopPolling();- _privateKey = null;- _requestId = null;- onError(MobileLoginErrorCode.Timeout);- return;- }-- throw new InvalidOperationException($"Polling failed: {response.StatusCode}");- }-- var result = await response.Content.ReadFromJsonAsync<MobileLoginPollResponse>();-- if (result?.Fulfilled == true && !string.IsNullOrEmpty(result.EncryptedSymmetricKey))- {- // Stop polling- StopPolling();-- // Decrypt the vault decryption key directly with RSA private key- var decryptionKey = await _jsInteropService.DecryptWithPrivateKey(result.EncryptedDecryptionKey!, _privateKey!);-- // Decrypt the symmetric key with RSA private key- var symmetricKeyBase64 = await _jsInteropService.DecryptWithPrivateKey(result.EncryptedSymmetricKey, _privateKey!);-- // Decrypt all remaining fields using the symmetric key- var token = await _jsInteropService.SymmetricDecrypt(result.EncryptedToken!, symmetricKeyBase64);- var refreshToken = await _jsInteropService.SymmetricDecrypt(result.EncryptedRefreshToken!, symmetricKeyBase64);- var username = await _jsInteropService.SymmetricDecrypt(result.EncryptedUsername!, symmetricKeyBase64);-- // Clear sensitive data- _privateKey = null;- _requestId = null;-- // Call success callback with decrypted data- await onSuccess(new MobileLoginResult- {- Username = username,- Token = token,- RefreshToken = refreshToken,- DecryptionKey = decryptionKey,- });- }- }- catch (Exception ex)- {- _logger.LogError(ex, "Error during mobile login polling");- StopPolling();- _privateKey = null;- _requestId = null;- onError(MobileLoginErrorCode.Generic);- }- }-}diff --git a/apps/server/AliasVault.Client/Utilities/MobileLoginErrorCode.cs b/apps/server/AliasVault.Client/Utilities/MobileLoginErrorCode.csdeleted file mode 100644index 58d738cac..000000000--- a/apps/server/AliasVault.Client/Utilities/MobileLoginErrorCode.cs+++ /dev/null@@ -1,30 +0,0 @@-//------------------------------------------------------------------------// <copyright file="MobileLoginErrorCode.cs" company="aliasvault">-// Copyright (c) aliasvault. All rights reserved.-// Licensed under the AGPLv3 license. See LICENSE.md file in the project root for full license information.-// </copyright>-//-------------------------------------------------------------------------namespace AliasVault.Client.Utilities;--/// <summary>-/// Error codes for mobile login operations.-/// These codes are used to provide translatable error messages to users.-/// </summary>-public enum MobileLoginErrorCode-{- /// <summary>- /// The mobile login request has timed out after 2 minutes.- /// </summary>- Timeout,-- /// <summary>- /// The request was declined on the mobile device.- /// </summary>- Declined,-- /// <summary>- /// A generic error occurred during mobile login.- /// </summary>- Generic,-}diff --git a/apps/server/AliasVault.Client/Utilities/MobileLoginException.cs b/apps/server/AliasVault.Client/Utilities/MobileLoginException.csdeleted file mode 100644index 51e75a6aa..000000000--- a/apps/server/AliasVault.Client/Utilities/MobileLoginException.cs+++ /dev/null@@ -1,32 +0,0 @@-//------------------------------------------------------------------------// <copyright file="MobileLoginException.cs" company="aliasvault">-// Copyright (c) aliasvault. All rights reserved.-// Licensed under the AGPLv3 license. See LICENSE.md file in the project root for full license information.-// </copyright>-//-------------------------------------------------------------------------namespace AliasVault.Client.Utilities;--using System;--/// <summary>-/// Exception thrown during mobile login operations.-/// Contains a <see cref="MobileLoginErrorCode"/> for translation.-/// </summary>-public class MobileLoginException : Exception-{- /// <summary>- /// Initializes a new instance of the <see cref="MobileLoginException"/> class.- /// </summary>- /// <param name="errorCode">The error code.</param>- public MobileLoginException(MobileLoginErrorCode errorCode)- : base($"Mobile login failed with error code: {errorCode}")- {- ErrorCode = errorCode;- }-- /// <summary>- /// Gets the error code.- /// </summary>- public MobileLoginErrorCode ErrorCode { get; }-}