Privacy-first password manager with built-in email aliasing. Fully encrypted and self-hostable.
Remove unused test helpers and Rust core WASM bindings (#2439)
Leendert de Borst29413f511dd2
diff --git a/apps/server/Shared/AliasVault.Shared/AppInfo.cs b/apps/server/Shared/AliasVault.Shared/AppInfo.csindex 6072ac3e5..d68fa61a3 100644--- a/apps/server/Shared/AliasVault.Shared/AppInfo.cs+++ b/apps/server/Shared/AliasVault.Shared/AppInfo.cs@@ -123,10 +123,4 @@ public static class AppInforeturn version;}-- /// <summary>- /// Gets a short version string (major.minor).- /// </summary>- /// <returns>The short version string.</returns>- public static string GetShortVersion() => $"{VersionMajor}.{VersionMinor}";}diff --git a/apps/server/Shared/AliasVault.Shared/Providers/Time/TestTimeProvider.cs b/apps/server/Shared/AliasVault.Shared/Providers/Time/TestTimeProvider.csdeleted file mode 100644index 92f20a8ff..000000000--- a/apps/server/Shared/AliasVault.Shared/Providers/Time/TestTimeProvider.cs+++ /dev/null@@ -1,39 +0,0 @@-// ------------------------------------------------------------------------// <copyright file="TestTimeProvider.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.Shared.Providers.Time;--/// <summary>-/// Test time provider that allows mutating the current time for testing purposes.-/// </summary>-public class TestTimeProvider : ITimeProvider-{- private DateTime _currentTime = DateTime.UtcNow;-- /// <summary>- /// Gets current time in UTC.- /// </summary>- public DateTime UtcNow => _currentTime;-- /// <summary>- /// Set the current time to a specific date and time.- /// </summary>- /// <param name="dateTime">DateTime to set current time to.</param>- public void SetUtcNow(DateTime dateTime)- {- _currentTime = dateTime;- }-- /// <summary>- /// Advance current time by a specific time span.- /// </summary>- /// <param name="timeSpan">Amount of time to advance current time by.</param>- public void AdvanceBy(TimeSpan timeSpan)- {- _currentTime = _currentTime.Add(timeSpan);- }-}diff --git a/apps/server/Tests/AliasVault.E2ETests/AliasVault.E2ETests.csproj b/apps/server/Tests/AliasVault.E2ETests/AliasVault.E2ETests.csprojindex 00424967d..5c58d7c40 100644--- a/apps/server/Tests/AliasVault.E2ETests/AliasVault.E2ETests.csproj+++ b/apps/server/Tests/AliasVault.E2ETests/AliasVault.E2ETests.csproj@@ -29,6 +29,7 @@<PackageReference Include="Microsoft.AspNetCore.Mvc.Testing" Version="10.0.10" /><PackageReference Include="Microsoft.NET.Test.Sdk" Version="18.8.1" /><PackageReference Include="NUnit" Version="4.6.1" />+ <PackageReference Include="Otp.NET" Version="1.4.1" /><PackageReference Include="NUnit3TestAdapter" Version="6.2.0" /><PackageReference Include="NUnit.Analyzers" Version="4.14.0"><PrivateAssets>all</PrivateAssets>@@ -47,9 +48,7 @@<ItemGroup><ProjectReference Include="..\..\AliasVault.Admin\AliasVault.Admin.csproj" />- <ProjectReference Include="..\..\AliasVault.Api\AliasVault.Api.csproj" /><ProjectReference Include="..\..\Databases\AliasServerDb\AliasServerDb.csproj" />- <ProjectReference Include="..\..\Utilities\AliasVault.TotpGenerator\AliasVault.TotpGenerator.csproj" /><ProjectReference Include="..\AliasVault.IntegrationTests\AliasVault.IntegrationTests.csproj" /></ItemGroup>diff --git a/apps/server/Tests/AliasVault.E2ETests/Common/PlaywrightInputHelper.cs b/apps/server/Tests/AliasVault.E2ETests/Common/PlaywrightInputHelper.csindex e894931c9..37455e818 100644--- a/apps/server/Tests/AliasVault.E2ETests/Common/PlaywrightInputHelper.cs+++ b/apps/server/Tests/AliasVault.E2ETests/Common/PlaywrightInputHelper.cs@@ -13,64 +13,6 @@ namespace AliasVault.E2ETests.Common;/// <param name="page">The IPage instance for the current test.</param>public class PlaywrightInputHelper(IPage page){- private static readonly Random Random = new();-- /// <summary>- /// Generate a random string of specified length.- /// </summary>- /// <param name="length">Length of the string.</param>- /// <returns>The random generated string.</returns>- public static string GenerateRandomString(int length = 10)- {- const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";- return new string(Enumerable.Repeat(chars, length)- .Select(s => s[Random.Next(s.Length)]).ToArray());- }-- /// <summary>- /// Generate a random email address.- /// </summary>- /// <returns>The random email address.</returns>- public static string GenerateRandomEmail()- {- return $"{GenerateRandomString(5)}@example.com";- }-- /// <summary>- /// Generate a random number.- /// </summary>- /// <returns>The random number.</returns>- public static string GenerateRandomNumber()- {- return Random.Next(0, 10000).ToString();- }-- /// <summary>- /// Generate a random password of specified length.- /// </summary>- /// <param name="length">The length of the password.</param>- /// <returns>The random generated password.</returns>- public static string GenerateRandomPassword(int length = 12)- {- const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*()";- return new string(Enumerable.Repeat(chars, length)- .Select(s => s[Random.Next(s.Length)]).ToArray());- }-- /// <summary>- /// Generate a random birthdate between 1800 and current year in yyyy-MM-dd format.- /// </summary>- /// <returns>The random birthdate string.</returns>- public static string GenerateRandomBirthdate()- {- int minYear = 1800;- int maxYear = DateTime.Now.Year;- int year = Random.Next(minYear, maxYear + 1);- int month = Random.Next(1, 13);- int day = Random.Next(1, DateTime.DaysInMonth(year, month) + 1);- return $"{year:0000}-{month:00}-{day:00}";- }-/// <summary>/// Helper method to fill specified input fields on a page with given values./// </summary>@@ -88,79 +30,8 @@ public class PlaywrightInputHelper(IPage page)// If fieldValues dictionary is provided and the inputId is found in it, fill the input with the value.if (inputId is not null && fieldValues is not null && fieldValues.TryGetValue(inputId, out var fieldValue)){- // For service-url fields, check if the input already contains a prefilled "https://"- // If it does, and our value also starts with "https://", clear the field first to avoid "https://https://..." duplication- // Playwright's FillAsync doesn't clear the field by default if there's already a value- if (inputId.StartsWith("service-url-"))- {- var currentValue = await input.InputValueAsync();-- // If the current value is just "https://" (the prefill) and our value starts with "https://",- // we need to clear first, otherwise FillAsync appends and we get "https://https://..."- if (!string.IsNullOrEmpty(currentValue) && currentValue == "https://" && fieldValue.StartsWith("https://"))- {- await input.ClearAsync();- }- }-await input.FillAsync(fieldValue);}}}-- /// <summary>- /// Helper method to fill all empty input fields on a page with random data if not provided.- /// </summary>- /// <returns>Async task.</returns>- public async Task FillEmptyInputFieldsWithRandom()- {- var inputFields = page.Locator("input");- var skipIds = new List<string> { "searchWidget" };- var count = await inputFields.CountAsync();- for (int i = 0; i < count; i++)- {- var input = inputFields.Nth(i);- var inputType = await input.GetAttributeAsync("type");- var inputId = await input.GetAttributeAsync("id");-- // If is not empty, skip.- if (!string.IsNullOrEmpty(await input.InputValueAsync()))- {- continue;- }-- // If input type is a file, skip.- if (inputType == "file")- {- continue;- }-- // If skipIds contains the inputId, skip.- if (inputId is not null && skipIds.Contains(inputId))- {- continue;- }-- // Generate appropriate random data based on input type.- string randomData;-- // Check for birthdate field- if (inputId == "birthdate")- {- randomData = GenerateRandomBirthdate();- }- else- {- randomData = inputType switch- {- "email" => GenerateRandomEmail(),- "number" => GenerateRandomNumber(),- "password" => GenerateRandomPassword(),- _ => GenerateRandomString(), // Default for all other types.- };- }-- await input.FillAsync(randomData);- }- }}diff --git a/apps/server/Tests/AliasVault.E2ETests/Common/PlaywrightTest.cs b/apps/server/Tests/AliasVault.E2ETests/Common/PlaywrightTest.csindex f039ef64e..884662006 100644--- a/apps/server/Tests/AliasVault.E2ETests/Common/PlaywrightTest.cs+++ b/apps/server/Tests/AliasVault.E2ETests/Common/PlaywrightTest.cs@@ -104,15 +104,6 @@ public abstract class PlaywrightTest}}- /// <summary>- /// Get the current relative URL.- /// </summary>- /// <returns>Current page as relative URL.</returns>- protected string GetCurrentRelativeUrl()- {- return Page.Url.Replace(AppBaseUrl, string.Empty);- }-/// <summary>/// Navigate to a relative URL using Blazor's client-side router./// </summary>@@ -238,35 +229,6 @@ public abstract class PlaywrightTest};}- /// <summary>- /// Sets new random test user credentials that are used for signing up and logging in.- /// </summary>- protected void SetRandomTestUserCredentials()- {- TestUserUsername = $"{Guid.NewGuid().ToString()[..10]}@test.com";- TestUserPassword = Guid.NewGuid().ToString();- }-- /// <summary>- /// Wait for the page to be fully loaded and the specified element to be visible and enabled.- /// </summary>- /// <param name="selector">The element to wait for and get.</param>- /// <returns>The requested element or a timeout if element was not found in time.</returns>- protected async Task<ILocator> WaitForAndGetElement(string selector)- {- var requestedElement = Page.Locator(selector);- await Page.WaitForLoadStateAsync(LoadState.NetworkIdle);-- // Wait for the requested element to be visible and enabled.- await requestedElement.WaitForAsync(new LocatorWaitForOptions- {- State = WaitForSelectorState.Visible,- Timeout = 10000,- });-- return requestedElement;- }-/// <summary>/// Set up the Playwright test environment. This method is required to be implemented by the derived class./// </summary>diff --git a/apps/server/Tests/AliasVault.E2ETests/Infrastructure/WebApplicationApiFactoryFixture.cs b/apps/server/Tests/AliasVault.E2ETests/Infrastructure/WebApplicationApiFactoryFixture.csdeleted file mode 100644index 47ce4ab61..000000000--- a/apps/server/Tests/AliasVault.E2ETests/Infrastructure/WebApplicationApiFactoryFixture.cs+++ /dev/null@@ -1,55 +0,0 @@-//------------------------------------------------------------------------// <copyright file="WebApplicationApiFactoryFixture.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.E2ETests.Infrastructure;--using AliasVault.E2ETests.Infrastructure.Abstracts;-using AliasVault.Shared.Providers.Time;-using Microsoft.Extensions.DependencyInjection;--/// <summary>-/// API web application factory fixture for integration tests.-/// </summary>-/// <typeparam name="TEntryPoint">The entry point.</typeparam>-public class WebApplicationApiFactoryFixture<TEntryPoint> : WebApplicationFactoryFixture<TEntryPoint>- where TEntryPoint : class-{- /// <summary>- /// Gets or sets the port the web application kestrel host will listen on.- /// </summary>- public override int Port { get; set; } = 5001;-- /// <summary>- /// Gets the time provider instance for mutating the current time in tests.- /// </summary>- public TestTimeProvider TimeProvider { get; private set; } = new();-- /// <summary>- /// Removes existing service registrations.- /// </summary>- /// <param name="services">The <see cref="IServiceCollection"/> to modify.</param>- protected override void RemoveExistingRegistrations(IServiceCollection services)- {- var descriptorsToRemove = services.Where(d =>- d.ServiceType == typeof(ITimeProvider)).ToList();-- foreach (var descriptor in descriptorsToRemove)- {- services.Remove(descriptor);- }- }-- /// <summary>- /// Adds new service registrations.- /// </summary>- /// <param name="services">The <see cref="IServiceCollection"/> to modify.</param>- protected override void AddNewRegistrations(IServiceCollection services)- {- // Add TestTimeProvider- services.AddSingleton<ITimeProvider>(TimeProvider);- }-}diff --git a/apps/server/Tests/AliasVault.E2ETests/Tests/Admin/TwoFactorAuthLockoutTests.cs b/apps/server/Tests/AliasVault.E2ETests/Tests/Admin/TwoFactorAuthLockoutTests.csindex fc26d6272..117fc7fbe 100644--- a/apps/server/Tests/AliasVault.E2ETests/Tests/Admin/TwoFactorAuthLockoutTests.cs+++ b/apps/server/Tests/AliasVault.E2ETests/Tests/Admin/TwoFactorAuthLockoutTests.cs@@ -7,6 +7,8 @@namespace AliasVault.E2ETests.Tests.Admin;+using OtpNet;+/// <summary>/// End-to-end tests for two-factor auth lockout behavior./// </summary>@@ -35,8 +37,8 @@ public class TwoFactorAuthLockoutTests : AdminPlaywrightTest// Extract secret key from page.var secretKey = await Page.TextContentAsync("kbd");- // Generate verification code with TotpHelper.- var totp = TotpGenerator.TotpGenerator.GenerateTotpCode(secretKey!);+ // Generate verification code.+ var totp = new Totp(Base32Encoding.ToBytes(secretKey!.Replace(" ", string.Empty))).ComputeTotp();// Fill in the form name="Input.Code".await Page.Locator("input[id='code']").FillAsync(totp);diff --git a/apps/server/Tests/AliasVault.UnitTests/AliasVault.UnitTests.csproj b/apps/server/Tests/AliasVault.UnitTests/AliasVault.UnitTests.csprojindex 0b76ad3fb..f0cd3e096 100644--- a/apps/server/Tests/AliasVault.UnitTests/AliasVault.UnitTests.csproj+++ b/apps/server/Tests/AliasVault.UnitTests/AliasVault.UnitTests.csproj@@ -46,7 +46,6 @@<PrivateAssets>all</PrivateAssets><IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets></PackageReference>- <PackageReference Include="Microsoft.EntityFrameworkCore.InMemory" Version="10.0.10" /></ItemGroup><ItemGroup>@@ -55,7 +54,6 @@<ProjectReference Include="..\..\Databases\AliasServerDb\AliasServerDb.csproj" /><ProjectReference Include="..\..\Utilities\AliasVault.Cryptography\AliasVault.Cryptography.csproj" /><ProjectReference Include="..\..\Utilities\AliasVault.FaviconExtractor\AliasVault.FaviconExtractor.csproj" />- <ProjectReference Include="..\..\Utilities\AliasVault.TotpGenerator\AliasVault.TotpGenerator.csproj" /></ItemGroup></Project>diff --git a/apps/server/Tests/AliasVault.UnitTests/Utilities/TotpGeneratorTests.cs b/apps/server/Tests/AliasVault.UnitTests/Utilities/TotpGeneratorTests.csdeleted file mode 100644index 766339394..000000000--- a/apps/server/Tests/AliasVault.UnitTests/Utilities/TotpGeneratorTests.cs+++ /dev/null@@ -1,158 +0,0 @@-//------------------------------------------------------------------------// <copyright file="TotpGeneratorTests.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.UnitTests.Utilities;--/// <summary>-/// Tests for the TotpGeneratorTests class.-/// </summary>-public class TotpGeneratorTests-{- private const string TestSecretKey = "JBSWY3DPEHPK3PXP";-- /// <summary>- /// Tests if the GenerateTotpCode method returns a valid code.- /// </summary>- [Test]- public void GenerateTotpCode_ReturnsValidCode()- {- string code = TotpGenerator.TotpGenerator.GenerateTotpCode(TestSecretKey);- Assert.That(code, Has.Length.EqualTo(6));- Assert.That(code, Does.Match(@"^\d{6}$"));- }-- /// <summary>- /// Tests if the GenerateTotpCode method returns a code with the correct length.- /// </summary>- [Test]- public void GenerateTotpCode_WithCustomDigits_ReturnsCodeWithCorrectLength()- {- string code = TotpGenerator.TotpGenerator.GenerateTotpCode(TestSecretKey, digits: 8);- Assert.That(code, Has.Length.EqualTo(8));- Assert.That(code, Does.Match(@"^\d{8}$"));- }-- /// <summary>- /// Tests if the GenerateTotpCode method returns a code when the secret key contains spaces and hyphens.- /// </summary>- [Test]- public void GenerateTotpCode_WithSpacesAndHyphens_ReturnsValidCode()- {- string secretWithSpacesAndHyphens = "JBSW Y3DP-EHPK 3PXP";- string code = TotpGenerator.TotpGenerator.GenerateTotpCode(secretWithSpacesAndHyphens);- Assert.That(code, Has.Length.EqualTo(6));- Assert.That(code, Does.Match(@"^\d{6}$"));- }-- /// <summary>- /// Tests if the VerifyTotpCode method returns true for a valid code.- /// </summary>- [Test]- public void VerifyTotpCode_WithValidCode_ReturnsTrue()- {- string code = TotpGenerator.TotpGenerator.GenerateTotpCode(TestSecretKey);- bool isValid = TotpGenerator.TotpGenerator.VerifyTotpCode(TestSecretKey, code);- Assert.That(isValid, Is.True);- }-- /// <summary>- /// Tests if the VerifyTotpCode method returns false for an invalid code.- /// </summary>- [Test]- public void VerifyTotpCode_WithInvalidCode_ReturnsFalse()- {- string invalidCode = "000000";- bool isValid = TotpGenerator.TotpGenerator.VerifyTotpCode(TestSecretKey, invalidCode);- Assert.That(isValid, Is.False);- }-- /// <summary>- /// Tests if the VerifyTotpCode method throws an exception for an invalid secret key.- /// </summary>- [Test]- public void GenerateTotpCode_WithInvalidSecretKey_ThrowsException()- {- string invalidSecret = "INVALID!@#";- Assert.Throws<ArgumentException>(() => TotpGenerator.TotpGenerator.GenerateTotpCode(invalidSecret));- }-- /// <summary>- /// Tests that each supported algorithm produces a well-formed code and that SHA256/SHA512 do not- /// silently fall back to SHA1 (which would generate codes the service rejects).- /// </summary>- /// <param name="algorithm">The HMAC algorithm to generate with.</param>- [Test]- [TestCase("SHA1")]- [TestCase("SHA256")]- [TestCase("SHA512")]- public void GenerateTotpCode_WithAlgorithm_ReturnsValidCode(string algorithm)- {- string code = TotpGenerator.TotpGenerator.GenerateTotpCode(TestSecretKey, algorithm: algorithm);- Assert.That(code, Does.Match(@"^\d{6}$"));- Assert.That(TotpGenerator.TotpGenerator.VerifyTotpCode(TestSecretKey, code, algorithm: algorithm), Is.True);- }-- /// <summary>- /// Tests that a code generated with SHA256 does not verify as SHA1, proving the algorithm actually- /// reaches the HMAC rather than being accepted and ignored.- /// </summary>- [Test]- public void GenerateTotpCode_WithSha256_DoesNotVerifyAsSha1()- {- string code = TotpGenerator.TotpGenerator.GenerateTotpCode(TestSecretKey, algorithm: "SHA256");- Assert.That(TotpGenerator.TotpGenerator.VerifyTotpCode(TestSecretKey, code, algorithm: "SHA1"), Is.False);- }-- /// <summary>- /// Tests that an unrecognized algorithm degrades to SHA1 instead of throwing, so one bad imported- /// value cannot make an item unreadable.- /// </summary>- [Test]- public void GenerateTotpCode_WithUnknownAlgorithm_FallsBackToSha1()- {- string code = TotpGenerator.TotpGenerator.GenerateTotpCode(TestSecretKey, algorithm: "MD5");- Assert.That(code, Is.EqualTo(TotpGenerator.TotpGenerator.GenerateTotpCode(TestSecretKey, algorithm: "SHA1")));- }-- /// <summary>- /// Tests that an otpauth:// URI's algorithm, digits and period are preserved rather than discarded.- /// </summary>- [Test]- public void SanitizeSecretKey_WithParameters_PreservesThem()- {- var (secretKey, _, parameters) = TotpGenerator.TotpHelper.SanitizeSecretKey($"otpauth://totp/Example:[email protected]?secret={TestSecretKey}&issuer=Example&algorithm=SHA512&digits=8&period=60");-- Assert.Multiple(() =>- {- Assert.That(secretKey, Is.EqualTo(TestSecretKey));- Assert.That(parameters.Algorithm, Is.EqualTo("SHA512"));- Assert.That(parameters.Digits, Is.EqualTo(8));- Assert.That(parameters.Period, Is.EqualTo(60));- });- }-- /// <summary>- /// Tests that an otpauth:// URI without parameters yields the RFC 6238 defaults.- /// </summary>- [Test]- public void SanitizeSecretKey_WithoutParameters_ReturnsDefaults()- {- var (_, _, parameters) = TotpGenerator.TotpHelper.SanitizeSecretKey($"otpauth://totp/Example:[email protected]?secret={TestSecretKey}&issuer=Example");- Assert.That(parameters, Is.EqualTo(TotpGenerator.TotpParameters.Default));- }-- /// <summary>- /// Tests that out-of-range or nonsense parameters are normalized to the defaults instead of being- /// stored as-is and breaking code generation later.- /// </summary>- [Test]- public void SanitizeSecretKey_WithInvalidParameters_NormalizesToDefaults()- {- var (_, _, parameters) = TotpGenerator.TotpHelper.SanitizeSecretKey($"otpauth://totp/Example?secret={TestSecretKey}&algorithm=ROT13&digits=99&period=0");- Assert.That(parameters, Is.EqualTo(TotpGenerator.TotpParameters.Default));- }-}diff --git a/apps/server/Utilities/AliasVault.TotpGenerator/AliasVault.TotpGenerator.csproj b/apps/server/Utilities/AliasVault.TotpGenerator/AliasVault.TotpGenerator.csprojdeleted file mode 100644index fb6f09e54..000000000--- a/apps/server/Utilities/AliasVault.TotpGenerator/AliasVault.TotpGenerator.csproj+++ /dev/null@@ -1,34 +0,0 @@-<Project Sdk="Microsoft.NET.Sdk">-- <PropertyGroup>- <TargetFramework>net10.0</TargetFramework>- <ImplicitUsings>enable</ImplicitUsings>- <Nullable>enable</Nullable>- <LangVersion>14</LangVersion>- </PropertyGroup>-- <PropertyGroup Condition=" '$(Configuration)' == 'Debug' ">- <TreatWarningsAsErrors>true</TreatWarningsAsErrors>- <DocumentationFile>bin\Debug\net10.0\TotpGenerator.xml</DocumentationFile>- </PropertyGroup>-- <PropertyGroup Condition=" '$(Configuration)' == 'Release' ">- <TreatWarningsAsErrors>true</TreatWarningsAsErrors>- <DocumentationFile>bin\Release\net10.0\TotpGenerator.xml</DocumentationFile>- </PropertyGroup>-- <ItemGroup>- <PackageReference Include="Otp.NET" Version="1.4.1" />- <PackageReference Include="StyleCop.Analyzers" Version="1.2.0-beta.556">- <PrivateAssets>all</PrivateAssets>- <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>- </PackageReference>- </ItemGroup>-- <ItemGroup>- <AdditionalFiles Include="..\..\stylecop.json">- <Link>stylecop.json</Link>- </AdditionalFiles>- </ItemGroup>--</Project>diff --git a/apps/server/Utilities/AliasVault.TotpGenerator/TotpGenerator.cs b/apps/server/Utilities/AliasVault.TotpGenerator/TotpGenerator.csdeleted file mode 100644index 27e527e1f..000000000--- a/apps/server/Utilities/AliasVault.TotpGenerator/TotpGenerator.cs+++ /dev/null@@ -1,77 +0,0 @@-//------------------------------------------------------------------------// <copyright file="TotpGenerator.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.TotpGenerator;--using OtpNet;--/// <summary>-/// Helper class to generate time based one-time passwords.-/// </summary>-public static class TotpGenerator-{- /// <summary>- /// Generates a Time-based One-Time Password (TOTP) for the given secret key.- /// </summary>- /// <param name="secretKey">The secret key in Base32 encoding.</param>- /// <param name="digits">The number of digits in the generated code. Default is 6.</param>- /// <param name="step">The time step in seconds. Default is 30.</param>- /// <param name="algorithm">The HMAC algorithm: SHA1, SHA256 or SHA512. Default is SHA1.</param>- /// <returns>The generated TOTP code.</returns>- public static string GenerateTotpCode(string secretKey, int digits = 6, int step = 30, string algorithm = TotpParameters.DefaultAlgorithm)- {- // Remove any whitespace and hyphens from the secret key- secretKey = secretKey.Replace(" ", string.Empty).Replace("-", string.Empty);-- // Convert the secret key from Base32 to byte array- byte[] keyBytes = Base32Encoding.ToBytes(secretKey);-- // Create a new TOTP instance- var totp = new Totp(keyBytes, step: step, mode: HashMode(algorithm), totpSize: digits);-- // Generate and return the current TOTP code- return totp.ComputeTotp();- }-- /// <summary>- /// Verifies a given TOTP code against the secret key.- /// </summary>- /// <param name="secretKey">The secret key in Base32 encoding.</param>- /// <param name="totpCode">The TOTP code to verify.</param>- /// <param name="digits">The number of digits in the code. Default is 6.</param>- /// <param name="step">The time step in seconds. Default is 30.</param>- /// <param name="timeWindowOffset">The time window offset for verification. Default is 1 (allows 1 step before and after).</param>- /// <param name="algorithm">The HMAC algorithm: SHA1, SHA256 or SHA512. Default is SHA1.</param>- /// <returns>True if the code is valid, false otherwise.</returns>- public static bool VerifyTotpCode(string secretKey, string totpCode, int digits = 6, int step = 30, int timeWindowOffset = 1, string algorithm = TotpParameters.DefaultAlgorithm)- {- // Remove any whitespace and hyphens from the secret key- secretKey = secretKey.Replace(" ", string.Empty).Replace("-", string.Empty);-- // Convert the secret key from Base32 to byte array- byte[] keyBytes = Base32Encoding.ToBytes(secretKey);-- // Create a new TOTP instance- var totp = new Totp(keyBytes, step: step, mode: HashMode(algorithm), totpSize: digits);-- // Verify the TOTP code- return totp.VerifyTotp(totpCode, out _, new VerificationWindow(previous: timeWindowOffset, future: timeWindowOffset));- }-- /// <summary>- /// Maps a TOTP algorithm name to its Otp.NET hash mode. An unrecognized name falls back to SHA1,- /// which is what RFC 6238 assumes, rather than failing the whole code.- /// </summary>- /// <param name="algorithm">The algorithm name.</param>- /// <returns>The matching hash mode.</returns>- private static OtpHashMode HashMode(string algorithm) => TotpParameters.NormalizeAlgorithm(algorithm) switch- {- "SHA256" => OtpHashMode.Sha256,- "SHA512" => OtpHashMode.Sha512,- _ => OtpHashMode.Sha1,- };-}diff --git a/apps/server/Utilities/AliasVault.TotpGenerator/TotpHelper.cs b/apps/server/Utilities/AliasVault.TotpGenerator/TotpHelper.csdeleted file mode 100644index 25f86b957..000000000--- a/apps/server/Utilities/AliasVault.TotpGenerator/TotpHelper.cs+++ /dev/null@@ -1,91 +0,0 @@-//------------------------------------------------------------------------// <copyright file="TotpHelper.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.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. Any algorithm/digits/period parameters carried by- /// the URI are returned alongside the secret so they can be stored rather than silently defaulted.- /// </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, name and TOTP parameters.</returns>- public static (string SecretKey, string? Name, TotpParameters Parameters) SanitizeSecretKey(string secretKey, string? name = null)- {- var parameters = TotpParameters.Default;-- // 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");-- // Keep the URI's TOTP parameters; without them an imported code that uses e.g. SHA256- // or an 8-digit length would silently generate codes the service rejects.- parameters = new TotpParameters(- TotpParameters.NormalizeAlgorithm(queryParams["algorithm"]),- TotpParameters.NormalizeDigits(queryParams["digits"]),- TotpParameters.NormalizePeriod(queryParams["period"]));-- // 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 = System.Web.HttpUtility.UrlDecode(uri.AbsolutePath.TrimStart('/'));-- // Check if there's an issuer in the query params- var issuer = queryParams["issuer"];-- // If the label contains ':', it might be in the format "issuer:account"- // Only split if there's no issuer in query params (to avoid splitting account names with colons)- if (label.Contains(':') && string.IsNullOrWhiteSpace(issuer))- {- // Split on the first colon only- var colonIndex = label.IndexOf(':');- name = label.Substring(colonIndex + 1);- }- else- {- name = label;- }-- // If there's an issuer in the query params, use it as a prefix- 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, parameters.Digits, parameters.Period, parameters.Algorithm);- }- catch (Exception)- {- throw new ArgumentException("Invalid secret key. Please check and try again.");- }-- return (secretKey, name, parameters);- }-}diff --git a/apps/server/Utilities/AliasVault.TotpGenerator/TotpParameters.cs b/apps/server/Utilities/AliasVault.TotpGenerator/TotpParameters.csdeleted file mode 100644index 7eaca5b3b..000000000--- a/apps/server/Utilities/AliasVault.TotpGenerator/TotpParameters.cs+++ /dev/null@@ -1,78 +0,0 @@-//------------------------------------------------------------------------// <copyright file="TotpParameters.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.TotpGenerator;--/// <summary>-/// The RFC 6238 parameters a TOTP code is generated with, and the normalization applied to values-/// read from an <c>otpauth://</c> URI or an imported vault.-/// </summary>-/// <param name="Algorithm">The HMAC algorithm: SHA1, SHA256 or SHA512.</param>-/// <param name="Digits">The number of digits in the generated code.</param>-/// <param name="Period">The time step in seconds a code stays valid for.</param>-public readonly record struct TotpParameters(string Algorithm, int Digits, int Period)-{- /// <summary>- /// The HMAC algorithm RFC 6238 assumes when an <c>otpauth://</c> URI omits the <c>algorithm</c> parameter.- /// </summary>- public const string DefaultAlgorithm = "SHA1";-- /// <summary>- /// The code length RFC 6238 assumes when an <c>otpauth://</c> URI omits the <c>digits</c> parameter.- /// </summary>- public const int DefaultDigits = 6;-- /// <summary>- /// The time step RFC 6238 assumes when an <c>otpauth://</c> URI omits the <c>period</c> parameter.- /// </summary>- public const int DefaultPeriod = 30;-- /// <summary>- /// Gets the parameters every TOTP code falls back to when none were specified.- /// </summary>- public static TotpParameters Default => new(DefaultAlgorithm, DefaultDigits, DefaultPeriod);-- /// <summary>- /// Normalizes a raw algorithm value to SHA1, SHA256 or SHA512, falling back to <see cref="DefaultAlgorithm"/>.- /// </summary>- /// <param name="value">Raw algorithm value, e.g. "sha256" or null.</param>- /// <returns>A supported algorithm name in uppercase.</returns>- public static string NormalizeAlgorithm(string? value)- {- var normalized = (value ?? string.Empty).Trim().ToUpperInvariant().Replace("-", string.Empty).Replace("_", string.Empty);- return normalized is "SHA1" or "SHA256" or "SHA512" ? normalized : DefaultAlgorithm;- }-- /// <summary>- /// Normalizes a raw digits value to a supported code length, falling back to <see cref="DefaultDigits"/>.- /// The 6-8 range matches what the authenticator ecosystem issues and what the mobile generators can compute.- /// </summary>- /// <param name="value">Raw digits value, e.g. "8" or null.</param>- /// <returns>A usable digit count.</returns>- public static int NormalizeDigits(string? value) => int.TryParse(value, out var parsed) ? NormalizeDigits(parsed) : DefaultDigits;-- /// <summary>- /// Normalizes a digits value to a supported code length, falling back to <see cref="DefaultDigits"/>.- /// </summary>- /// <param name="value">Raw digits value.</param>- /// <returns>A usable digit count.</returns>- public static int NormalizeDigits(int value) => value is >= 6 and <= 8 ? value : DefaultDigits;-- /// <summary>- /// Normalizes a raw period value to a positive time step, falling back to <see cref="DefaultPeriod"/>.- /// </summary>- /// <param name="value">Raw period value, e.g. "60" or null.</param>- /// <returns>A usable period in seconds.</returns>- public static int NormalizePeriod(string? value) => int.TryParse(value, out var parsed) ? NormalizePeriod(parsed) : DefaultPeriod;-- /// <summary>- /// Normalizes a period value to a positive time step, falling back to <see cref="DefaultPeriod"/>.- /// </summary>- /// <param name="value">Raw period value.</param>- /// <returns>A usable period in seconds.</returns>- public static int NormalizePeriod(int value) => value is > 0 and <= 300 ? value : DefaultPeriod;-}diff --git a/apps/server/aliasvault.sln b/apps/server/aliasvault.slnindex 395157efd..cdfc8f5c9 100644--- a/apps/server/aliasvault.sln+++ b/apps/server/aliasvault.sln@@ -35,8 +35,6 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AliasVault.Logging", "UtiliEndProjectProject("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AliasVault.WorkerStatus", "Utilities\AliasVault.WorkerStatus\AliasVault.WorkerStatus.csproj", "{951C3DF8-DF22-4B2B-839F-FBA26DDD8ABD}"EndProject-Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AliasVault.TotpGenerator", "Utilities\AliasVault.TotpGenerator\AliasVault.TotpGenerator.csproj", "{E8D9C551-67D2-4651-8EDF-4262DF7375CE}"-EndProjectProject("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AliasVault.Auth", "Utilities\AliasVault.Auth\AliasVault.Auth.csproj", "{DA175274-0FF7-4436-9266-742F96C2D1ED}"EndProjectProject("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AliasVault.Cryptography", "Utilities\AliasVault.Cryptography\AliasVault.Cryptography.csproj", "{341EC443-0B6B-4E8C-AF46-D6156573CEA5}"@@ -105,10 +103,6 @@ Global{951C3DF8-DF22-4B2B-839F-FBA26DDD8ABD}.Debug|Any CPU.Build.0 = Debug|Any CPU{951C3DF8-DF22-4B2B-839F-FBA26DDD8ABD}.Release|Any CPU.ActiveCfg = Release|Any CPU{951C3DF8-DF22-4B2B-839F-FBA26DDD8ABD}.Release|Any CPU.Build.0 = Release|Any CPU- {E8D9C551-67D2-4651-8EDF-4262DF7375CE}.Debug|Any CPU.ActiveCfg = Debug|Any CPU- {E8D9C551-67D2-4651-8EDF-4262DF7375CE}.Debug|Any CPU.Build.0 = Debug|Any CPU- {E8D9C551-67D2-4651-8EDF-4262DF7375CE}.Release|Any CPU.ActiveCfg = Release|Any CPU- {E8D9C551-67D2-4651-8EDF-4262DF7375CE}.Release|Any CPU.Build.0 = Release|Any CPU{DA175274-0FF7-4436-9266-742F96C2D1ED}.Debug|Any CPU.ActiveCfg = Debug|Any CPU{DA175274-0FF7-4436-9266-742F96C2D1ED}.Debug|Any CPU.Build.0 = Debug|Any CPU{DA175274-0FF7-4436-9266-742F96C2D1ED}.Release|Any CPU.ActiveCfg = Release|Any CPU@@ -140,7 +134,6 @@ Global{857BCD0E-753F-437A-AF75-B995B4D9A5FE} = {01AB9389-2F89-4F8E-A688-BF4BF1FC42C8}{FF0B0E64-1AE2-415C-A404-0EB78010821A} = {01AB9389-2F89-4F8E-A688-BF4BF1FC42C8}{951C3DF8-DF22-4B2B-839F-FBA26DDD8ABD} = {01AB9389-2F89-4F8E-A688-BF4BF1FC42C8}- {E8D9C551-67D2-4651-8EDF-4262DF7375CE} = {01AB9389-2F89-4F8E-A688-BF4BF1FC42C8}{DA175274-0FF7-4436-9266-742F96C2D1ED} = {01AB9389-2F89-4F8E-A688-BF4BF1FC42C8}{341EC443-0B6B-4E8C-AF46-D6156573CEA5} = {01AB9389-2F89-4F8E-A688-BF4BF1FC42C8}{34FADEB6-4B56-463B-B359-F844B43D76D9} = {DD359F0A-0180-4F8F-9E48-46213386BA4D}diff --git a/core/rust/src/bindings/wasm.rs b/core/rust/src/bindings/wasm.rsindex f7491c827..52597f529 100644--- a/core/rust/src/bindings/wasm.rs+++ b/core/rust/src/bindings/wasm.rs@@ -5,10 +5,7 @@ use wasm_bindgen::prelude::*;use crate::credential_matcher::{filter_credentials, CredentialMatcherInput, CredentialMatcherOutput};use crate::password_generator::{available_languages, generate_password};-use crate::vault_codec::{self, CanonicalizeInput, DataBucket, Manifest, MaterializeInput};-use crate::vault_merge::{merge_canonical, CanonicalMergeInput, CanonicalMergeOutput};-use crate::vault_sharing::{self, ManifestAccessRequest, ManifestWriteSetRequest};-use crate::vault_pruner::prune_vault;+use crate::vault_codec::{self, CanonicalizeInput};/// Initialize panic hook for better error messages.#[wasm_bindgen(start)]@@ -27,7 +24,7 @@ fn to_js<T: Serialize>(value: &T) -> Result<JsValue, JsValue> {}// ═══════════════════════════════════════════════════════════════════════════════-// Vault Merge WASM Bindings+// Vault Sync WASM Bindings// ═══════════════════════════════════════════════════════════════════════════════/// Get the list of table names that take part in a vault sync.@@ -36,37 +33,6 @@ pub fn get_syncable_table_names_js() -> Vec<String> {crate::vault_model::SYNCABLE_TABLE_NAMES.iter().map(|s| s.to_string()).collect()}-/// Merge the local canonical vault onto the server canonical vault (manifest-v1 format).-///-/// Takes a JsValue (CanonicalMergeInput) and returns a JsValue (CanonicalMergeOutput): the merged-/// manifests + data buckets, one entry per server manifest, rows out instead of SQL statements.-#[wasm_bindgen(js_name = mergeCanonical)]-pub fn merge_canonical_js(input: JsValue) -> Result<JsValue, JsValue> {- let input: CanonicalMergeInput = serde_wasm_bindgen::from_value(input).map_err(js_err)?;- let output: CanonicalMergeOutput = merge_canonical(input).map_err(js_err)?;- to_js(&output)-}--// ═══════════════════════════════════════════════════════════════════════════════-// Vault Pruner WASM Bindings-// ═══════════════════════════════════════════════════════════════════════════════--/// Prune expired items from trash (items with DeletedAt older than retention_days, default 30).-/// Input: `PruneInput` JSON. Output: `PruneOutput` JSON.-#[wasm_bindgen(js_name = pruneVaultJson)]-pub fn prune_vault_json_js(input_json: &str) -> Result<String, JsValue> {- crate::common::error::json_call(input_json, prune_vault).map_err(js_err)-}--/// Get the per-table SELECT queries used to build prune input.-///-/// Returns an array of `{ name, query }` objects. Blob columns are reduced to a-/// 1-byte presence marker to avoid serializing large binary data to JSON.-#[wasm_bindgen(js_name = getPruneTableQueries)]-pub fn get_prune_table_queries_js() -> Result<JsValue, JsValue> {- serde_wasm_bindgen::to_value(&crate::vault_pruner::get_prune_table_queries()).map_err(js_err)-}-// ═══════════════════════════════════════════════════════════════════════════════// Vault Codec WASM Bindings (manifest-v1 storage format)// ═══════════════════════════════════════════════════════════════════════════════@@ -94,15 +60,6 @@ pub fn vault_codec_canonicalize_from_sqlite_js(input: JsValue) -> Result<JsValueto_js(&output)}-/// Materialize the manifest + data buckets into the table set the platform inserts into a fresh schema DB.-/// Input: `MaterializeInput`. Output: `MaterializedTables`.-#[wasm_bindgen(js_name = vaultCodecMaterializeAsSqlite)]-pub fn vault_codec_materialize_as_sqlite_js(input: JsValue) -> Result<JsValue, JsValue> {- let input: MaterializeInput = serde_wasm_bindgen::from_value(input).map_err(js_err)?;- let output = vault_codec::materialize_as_sqlite(input).map_err(js_err)?;- to_js(&output)-}-/// Generate a fresh 32-byte per-manifest blob-hashing salt (lowercase hex).#[wasm_bindgen(js_name = vaultCodecGenerateManifestSalt)]pub fn vault_codec_generate_manifest_salt_js() -> String {@@ -121,62 +78,6 @@ pub fn vault_codec_unpack_payload_js(plain_bytes: &[u8]) -> Result<String, JsValvault_codec::unpack_payload(plain_bytes).map_err(js_err)}-/// Structurally validate a manifest. Input: `Manifest`. Output: `ValidationResult`.-#[wasm_bindgen(js_name = vaultCodecValidateManifest)]-pub fn vault_codec_validate_manifest_js(manifest: JsValue) -> Result<JsValue, JsValue> {- let m: Manifest = serde_wasm_bindgen::from_value(manifest).map_err(js_err)?;- serde_wasm_bindgen::to_value(&vault_codec::validate_manifest(&m)).map_err(js_err)-}--/// Validate a data bucket. Input: `DataBucket`. Output: `ValidationResult`.-#[wasm_bindgen(js_name = vaultCodecValidateDataBucket)]-pub fn vault_codec_validate_data_bucket_js(data_bucket: JsValue) -> Result<JsValue, JsValue> {- let b: DataBucket = serde_wasm_bindgen::from_value(data_bucket).map_err(js_err)?;- serde_wasm_bindgen::to_value(&vault_codec::validate_data_bucket(&b)).map_err(js_err)-}--/// SHA-256 (lowercase hex) of a base64 ciphertext string.-#[wasm_bindgen(js_name = vaultCodecComputeCiphertextHash)]-pub fn vault_codec_compute_ciphertext_hash_js(base64_ciphertext: &str) -> String {- vault_codec::compute_ciphertext_hash(base64_ciphertext)-}--/// Content fingerprint of a manifest / data-bucket payload JSON for change detection: SHA-256 (lowercase-/// hex) of the canonical JSON, excluding the volatile `canonicalizedAt` timestamp.-#[wasm_bindgen(js_name = vaultCodecComputeContentFingerprint)]-pub fn vault_codec_compute_content_fingerprint_js(payload_json: &str) -> String {- vault_codec::compute_content_fingerprint(payload_json)-}--/// Extract the encryption-key row whose `PublicKey` matches `public_key` from a decrypted manifest's-/// `EncryptionKeys` table (scoped to the manifest itself: personal keys on the personal manifest, the folder's-/// delivery keypair on a shared manifest).-#[wasm_bindgen(js_name = vaultCodecExtractEncryptionKeyForPublicKey)]-pub fn vault_codec_extract_encryption_key_for_public_key_js(manifest: JsValue, public_key: &str) -> Result<JsValue, JsValue> {- let m: Manifest = serde_wasm_bindgen::from_value(manifest).map_err(js_err)?;- to_js(&vault_codec::extract_encryption_key_for_public_key(&m, public_key))-}--// ═══════════════════════════════════════════════════════════════════════════════-// Vault Sharing WASM Bindings-// ═══════════════════════════════════════════════════════════════════════════════--/// Resolve which manifests the next push writes, personal manifest first.-/// Input: `ManifestWriteSetRequest`. Output: `ManifestWriteSet`.-#[wasm_bindgen(js_name = vaultSharingResolveManifestWriteSet)]-pub fn vault_sharing_resolve_manifest_write_set_js(input: JsValue) -> Result<JsValue, JsValue> {- let input: ManifestWriteSetRequest = serde_wasm_bindgen::from_value(input).map_err(js_err)?;- to_js(&vault_sharing::resolve_manifest_write_set(input))-}--/// Split what the vault holds into what cannot be written and what access was lost.-/// Input: `ManifestAccessRequest`. Output: `ManifestAccessPartition`.-#[wasm_bindgen(js_name = vaultSharingPartitionManifestAccess)]-pub fn vault_sharing_partition_manifest_access_js(input: JsValue) -> Result<JsValue, JsValue> {- let input: ManifestAccessRequest = serde_wasm_bindgen::from_value(input).map_err(js_err)?;- to_js(&vault_sharing::partition_manifest_access(input))-}-// ═══════════════════════════════════════════════════════════════════════════════// Credential Matcher WASM Bindings// ═══════════════════════════════════════════════════════════════════════════════diff --git a/core/rust/src/vault_pruner/mod.rs b/core/rust/src/vault_pruner/mod.rsindex 5a35897bf..eaa2d9ac2 100644--- a/core/rust/src/vault_pruner/mod.rs+++ b/core/rust/src/vault_pruner/mod.rs@@ -27,8 +27,8 @@ pub struct PruneInput {pub tables: Vec<CodecTableData>,/// Current time in ISO 8601 UTC format: `YYYY-MM-DDTHH:MM:SS.sssZ`./*- * Callers: JavaScript `new Date().toISOString()`, C# `DateTime.UtcNow.ToString("yyyy-MM-ddTHH:mm:ss.fffZ")`,- * Swift `ISO8601DateFormatter().string(from: Date())`, Kotlin `Instant.now().toString()`.+ * Callers: the Rust sync engine (`now_iso_utc()`), Swift `ISO8601DateFormatter().string(from: Date())`,+ * Kotlin `Instant.now().toString()`.*/pub current_time: String,/// Retention period in days (default: 30)