Privacy-first password manager with built-in email aliasing. Fully encrypted and self-hostable.
Add TOTP code sanitize to import (#542)
Leendert de Borst0e5f61167046
diff --git a/src/AliasVault.Client/Main/Components/TotpCodes/TotpCodes.razor b/src/AliasVault.Client/Main/Components/TotpCodes/TotpCodes.razorindex f92c4d0e9..2891d1d06 100644--- a/src/AliasVault.Client/Main/Components/TotpCodes/TotpCodes.razor+++ b/src/AliasVault.Client/Main/Components/TotpCodes/TotpCodes.razor@@ -140,62 +140,21 @@/// </summary>private async Task AddTotpCode(){- string secretKey = NewTotpCode.SecretKey;-- // Sanitize the secret key (remove whitespace and hyphens)- secretKey = secretKey.Replace(" ", string.Empty).Replace("-", string.Empty);- string? name = NewTotpCode.Name;-- // Check if the input is a TOTP URI- if (secretKey.StartsWith("otpauth://totp/"))- {- try- {- var uri = new Uri(secretKey);- var queryParams = System.Web.HttpUtility.ParseQueryString(uri.Query);-- // Extract the secret from query parameters- secretKey = queryParams["secret"] ?? throw new ArgumentException("Secret not found in URI");-- // If no name was provided, try to get it from the URI- if (string.IsNullOrWhiteSpace(name))- {- // The label is everything after 'totp/' and before '?'- var label = uri.AbsolutePath.TrimStart('/');- // If the label contains ':', take the part after it- name = label.Contains(':') ? label.Split(':')[1] : label;-- // If there's an issuer in the query params, use it as a prefix- var issuer = queryParams["issuer"];- if (!string.IsNullOrWhiteSpace(issuer))- {- name = $"{issuer}: {name}";- }- NewTotpCode.Name = name;- }- NewTotpCode.SecretKey = secretKey;- }- catch (Exception)- {- GlobalNotificationService.AddErrorMessage("Invalid TOTP URI format. Please check and try again.", true);- return;- }- }-- try- {- // Validate the secret key by trying to generate a code- TotpGenerator.GenerateTotpCode(secretKey);+ // Sanitize the secret key by converting from URI to secret key and name.+ try {+ var (secretKey, name) = TotpHelper.SanitizeSecretKey(NewTotpCode.SecretKey, NewTotpCode.Name);+ NewTotpCode.SecretKey = secretKey;+ NewTotpCode.Name = name;}- catch (Exception)+ catch (Exception ex){- GlobalNotificationService.AddErrorMessage("Invalid secret key. Please check and try again.", true);+ GlobalNotificationService.AddErrorMessage(ex.Message, true);return;}// Create a new TOTP code in memoryvar newTotpCode = NewTotpCode.ToEntity();- newTotpCode.Name = name ?? "Authenticator";+ newTotpCode.Name = NewTotpCode.Name ?? "Authenticator";// Add to the listTotpCodeList.Add(newTotpCode);diff --git a/src/Utilities/AliasVault.ImportExport/AliasVault.ImportExport.csproj b/src/Utilities/AliasVault.ImportExport/AliasVault.ImportExport.csprojindex 890d226ec..c86d4044d 100644--- a/src/Utilities/AliasVault.ImportExport/AliasVault.ImportExport.csproj+++ b/src/Utilities/AliasVault.ImportExport/AliasVault.ImportExport.csproj@@ -17,6 +17,7 @@<ItemGroup><ProjectReference Include="..\..\Databases\AliasClientDb\AliasClientDb.csproj" />+ <ProjectReference Include="..\..\Utilities\AliasVault.TotpGenerator\AliasVault.TotpGenerator.csproj" /></ItemGroup></Project>diff --git a/src/Utilities/AliasVault.ImportExport/Importers/BaseImporter.cs b/src/Utilities/AliasVault.ImportExport/Importers/BaseImporter.csindex 8459fe6d0..ed730a1eb 100644--- a/src/Utilities/AliasVault.ImportExport/Importers/BaseImporter.cs+++ b/src/Utilities/AliasVault.ImportExport/Importers/BaseImporter.cs@@ -9,6 +9,7 @@ namespace AliasVault.ImportExport.Importers;using AliasClientDb;using AliasVault.ImportExport.Models;+using AliasVault.TotpGenerator;/// <summary>/// Base class for all importers.@@ -51,12 +52,15 @@ public class BaseImporterif (!string.IsNullOrEmpty(importedCredential.TwoFactorSecret)){+ // Sanitize the secret key by converting from potential URI to secret key and name.+ var (secretKey, name) = TotpHelper.SanitizeSecretKey(importedCredential.TwoFactorSecret);+credential.TotpCodes = new List<TotpCode>{new(){- Name = "Authenticator",- SecretKey = importedCredential.TwoFactorSecret,+ Name = name ?? "Authenticator",+ SecretKey = secretKey,CreatedAt = importedCredential.CreatedAt ?? DateTime.UtcNow,UpdatedAt = importedCredential.UpdatedAt ?? DateTime.UtcNow,}diff --git a/src/Utilities/AliasVault.TotpGenerator/TotpHelper.cs b/src/Utilities/AliasVault.TotpGenerator/TotpHelper.csnew file mode 100644index 000000000..79cbc94e3--- /dev/null+++ b/src/Utilities/AliasVault.TotpGenerator/TotpHelper.cs@@ -0,0 +1,69 @@+//-----------------------------------------------------------------------+// <copyright file="TotpHelper.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.TotpGenerator;++/// <summary>+/// Helper class to verify and sanitize TOTP codes.+/// </summary>+public static class TotpHelper+{+ /// <summary>+ /// Sanitizes a TOTP secret if its provided as a URI.+ /// </summary>+ /// <param name="secretKey">The secret key in Base32 encoding.</param>+ /// <param name="name">The name of the TOTP code.</param>+ /// <returns>The sanitized secret key and name.</returns>+ public static (string SecretKey, string? Name) SanitizeSecretKey(string secretKey, string? name = null)+ {+ // Check if the input is a TOTP URI+ if (secretKey.StartsWith("otpauth://totp/"))+ {+ try+ {+ var uri = new Uri(secretKey);+ var queryParams = System.Web.HttpUtility.ParseQueryString(uri.Query);++ // Extract the secret from query parameters+ secretKey = queryParams["secret"] ?? throw new ArgumentException("Secret not found in URI");++ // If no name was provided, try to get it from the URI+ if (string.IsNullOrWhiteSpace(name))+ {+ // The label is everything after 'totp/' and before '?'+ var label = uri.AbsolutePath.TrimStart('/');++ // If the label contains ':', take the part after it+ name = label.Contains(':') ? label.Split(':')[1] : label;++ // If there's an issuer in the query params, use it as a prefix+ var issuer = queryParams["issuer"];+ if (!string.IsNullOrWhiteSpace(issuer))+ {+ name = $"{issuer}: {name}";+ }+ }+ }+ catch (Exception)+ {+ throw new ArgumentException("Invalid TOTP URI format. Please check and try again.");+ }+ }++ try+ {+ // Validate the secret key by trying to generate a code+ TotpGenerator.GenerateTotpCode(secretKey);+ }+ catch (Exception)+ {+ throw new ArgumentException("Invalid secret key. Please check and try again.");+ }++ return (secretKey, name);+ }+}