Privacy-first password manager with built-in email aliasing. Fully encrypted and self-hostable.
Refactoring (#44)
Leendert de Borstbb91637db5d0
diff --git a/.github/workflows/dotnet-build-run-tests.yml b/.github/workflows/dotnet-build-run-tests.ymlindex baa6bfbad..79f2a4f6e 100644--- a/.github/workflows/dotnet-build-run-tests.yml+++ b/.github/workflows/dotnet-build-run-tests.yml@@ -20,6 +20,8 @@ jobs:uses: actions/setup-dotnet@v4with:dotnet-version: 8.0.x+ - name: Install dependencies+ run: dotnet workload install wasm-tools- name: Restore dependenciesrun: dotnet restore- name: Builddiff --git a/.github/workflows/dotnet-integration-tests.yml b/.github/workflows/dotnet-integration-tests.ymlindex 5633f21f3..221052ab5 100644--- a/.github/workflows/dotnet-integration-tests.yml+++ b/.github/workflows/dotnet-integration-tests.yml@@ -19,6 +19,8 @@ jobs:uses: actions/setup-dotnet@v4with:dotnet-version: 8.0.x+ - name: Install dependencies+ run: dotnet workload install wasm-tools- name: Buildrun: dotnet build- name: Ensure browsers are installeddiff --git a/aliasvault.sln b/aliasvault.slnindex df4203bf4..f21e6e079 100644--- a/aliasvault.sln+++ b/aliasvault.sln@@ -23,8 +23,6 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Tests", "Tests", "{29DE523DEndProjectProject("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AliasVault.E2ETests", "src\Tests\AliasVault.E2ETests\AliasVault.E2ETests.csproj", "{AF013D08-1BF6-4E23-87D2-37F614BE7952}"EndProject-Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SqliteWasm", "src\Utilities\SqliteWasm\SqliteWasm.csproj", "{6DC107A8-4887-42EA-B16B-C9A7B6A0298B}"-EndProjectProject("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Database", "Database", "{5F7417F6-4388-49CC-9511-ED63C4A6488A}"EndProjectProject("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AliasServerDb", "src\Databases\AliasServerDb\AliasServerDb.csproj", "{1277105D-50CD-4CE0-9C2C-549F46867E54}"@@ -69,10 +67,6 @@ Global{AF013D08-1BF6-4E23-87D2-37F614BE7952}.Debug|Any CPU.Build.0 = Debug|Any CPU{AF013D08-1BF6-4E23-87D2-37F614BE7952}.Release|Any CPU.ActiveCfg = Release|Any CPU{AF013D08-1BF6-4E23-87D2-37F614BE7952}.Release|Any CPU.Build.0 = Release|Any CPU- {6DC107A8-4887-42EA-B16B-C9A7B6A0298B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU- {6DC107A8-4887-42EA-B16B-C9A7B6A0298B}.Debug|Any CPU.Build.0 = Debug|Any CPU- {6DC107A8-4887-42EA-B16B-C9A7B6A0298B}.Release|Any CPU.ActiveCfg = Release|Any CPU- {6DC107A8-4887-42EA-B16B-C9A7B6A0298B}.Release|Any CPU.Build.0 = Release|Any CPU{1277105D-50CD-4CE0-9C2C-549F46867E54}.Debug|Any CPU.ActiveCfg = Debug|Any CPU{1277105D-50CD-4CE0-9C2C-549F46867E54}.Debug|Any CPU.Build.0 = Debug|Any CPU{1277105D-50CD-4CE0-9C2C-549F46867E54}.Release|Any CPU.ActiveCfg = Release|Any CPU@@ -90,7 +84,6 @@ Global{8E6A418A-B305-465D-857D-49953605C18E} = {29DE523D-EEF2-41E9-AC12-F20D8D02BEBB}{427EA8E2-EA76-467E-A6BC-201EFE40C0D0} = {01AB9389-2F89-4F8E-A688-BF4BF1FC42C8}{AF013D08-1BF6-4E23-87D2-37F614BE7952} = {29DE523D-EEF2-41E9-AC12-F20D8D02BEBB}- {6DC107A8-4887-42EA-B16B-C9A7B6A0298B} = {01AB9389-2F89-4F8E-A688-BF4BF1FC42C8}{1277105D-50CD-4CE0-9C2C-549F46867E54} = {5F7417F6-4388-49CC-9511-ED63C4A6488A}{FE10F294-817F-477E-A24F-8597A15AF0B5} = {5F7417F6-4388-49CC-9511-ED63C4A6488A}EndGlobalSectiondiff --git a/database/AliasClientDb/AliasClientDbContext.cs b/database/AliasClientDb/AliasClientDbContext.csindex 9d71690b2..2cb129df2 100644--- a/database/AliasClientDb/AliasClientDbContext.cs+++ b/database/AliasClientDb/AliasClientDbContext.cs@@ -54,12 +54,12 @@ public class AliasClientDbContext : DbContext/// <summary>/// The OnModelCreating method./// </summary>- /// <param name="builder">ModelBuilder instance.</param>- protected override void OnModelCreating(ModelBuilder builder)+ /// <param name="modelBuilder">ModelBuilder instance.</param>+ protected override void OnModelCreating(ModelBuilder modelBuilder){- base.OnModelCreating(builder);+ base.OnModelCreating(modelBuilder);- foreach (var entity in builder.Model.GetEntityTypes())+ foreach (var entity in modelBuilder.Model.GetEntityTypes()){foreach (var property in entity.GetProperties()){diff --git a/src/AliasVault.Api/Controllers/AuthController.cs b/src/AliasVault.Api/Controllers/AuthController.csindex 487801942..04bebbee0 100644--- a/src/AliasVault.Api/Controllers/AuthController.cs+++ b/src/AliasVault.Api/Controllers/AuthController.cs@@ -276,6 +276,20 @@ public class AuthController(AliasServerDbContext context, UserManager<AliasVaultreturn principal;}+ /// <summary>+ /// Generate a refresh token for a user. This token is used to request a new access token when the current+ /// access token expires. The refresh token is long-lived by design.+ /// </summary>+ /// <returns>Random string to be used as refresh token.</returns>+ private static string GenerateRefreshToken()+ {+ var randomNumber = new byte[32];+ using var rng = RandomNumberGenerator.Create();++ rng.GetBytes(randomNumber);+ return Convert.ToBase64String(randomNumber);+ }+/// <summary>/// Generate a Jwt access token for a user. This token is used to authenticate the user for a limited time/// and is short-lived by design. With the separate refresh token, the user can request a new access token@@ -306,20 +320,6 @@ public class AuthController(AliasServerDbContext context, UserManager<AliasVaultreturn new JwtSecurityTokenHandler().WriteToken(token);}- /// <summary>- /// Generate a refresh token for a user. This token is used to request a new access token when the current- /// access token expires. The refresh token is long-lived by design.- /// </summary>- /// <returns>Random string to be used as refresh token.</returns>- private string GenerateRefreshToken()- {- var randomNumber = new byte[32];- using var rng = RandomNumberGenerator.Create();-- rng.GetBytes(randomNumber);- return Convert.ToBase64String(randomNumber);- }-/// <summary>/// Generates a new access and refresh token for a user and persists the refresh token/// to the database.diff --git a/src/AliasVault.Api/Dockerfile b/src/AliasVault.Api/Dockerfileindex ad89ecd43..7202a45a4 100644--- a/src/AliasVault.Api/Dockerfile+++ b/src/AliasVault.Api/Dockerfile@@ -9,7 +9,7 @@ WORKDIR /src# Copy the project files and restore dependenciesCOPY ["src/AliasVault.Api/AliasVault.Api.csproj", "src/AliasVault.Api/"]-COPY ["src/AliasServerDb/AliasServerDb.csproj", "src/AliasServerDb/"]+COPY ["src/Databases/AliasServerDb/AliasServerDb.csproj", "src/Databases/AliasServerDb/"]COPY ["src/AliasVault.Shared/AliasVault.Shared.csproj", "src/AliasVault.Shared/"]COPY ["src/AliasGenerators/AliasGenerators.csproj", "src/AliasGenerators/"]RUN dotnet restore "src/AliasVault.Api/AliasVault.Api.csproj"diff --git a/src/AliasVault.WebApp/AliasVault.WebApp.csproj b/src/AliasVault.WebApp/AliasVault.WebApp.csprojindex aca386f1a..aa30b45a9 100644--- a/src/AliasVault.WebApp/AliasVault.WebApp.csproj+++ b/src/AliasVault.WebApp/AliasVault.WebApp.csproj@@ -75,7 +75,6 @@<ProjectReference Include="..\AliasVault.Shared\AliasVault.Shared.csproj" /><ProjectReference Include="..\Utilities\Cryptography\Cryptography.csproj" /><ProjectReference Include="..\Utilities\FaviconExtractor\FaviconExtractor.csproj" />- <ProjectReference Include="..\Utilities\SqliteWasm\SqliteWasm.csproj" /></ItemGroup><ItemGroup>diff --git a/src/AliasVault.WebApp/Dockerfile b/src/AliasVault.WebApp/Dockerfileindex d978df75c..400db26ea 100644--- a/src/AliasVault.WebApp/Dockerfile+++ b/src/AliasVault.WebApp/Dockerfile@@ -7,10 +7,13 @@ FROM mcr.microsoft.com/dotnet/sdk:8.0 AS buildARG BUILD_CONFIGURATION=ReleaseWORKDIR /src+# Install the WebAssembly tools+RUN dotnet workload install wasm-tools+# Copy the project files and restore dependenciesCOPY ["src/AliasVault.WebApp/AliasVault.WebApp.csproj", "src/AliasVault.WebApp/"]COPY ["src/AliasVault.Shared/AliasVault.Shared.csproj", "src/AliasVault.Shared/"]-COPY ["src/AliasServerDb/AliasServerDb.csproj", "src/AliasServerDb/"]+COPY ["src/Databases/AliasServerDb/AliasServerDb.csproj", "src/Databases/AliasServerDb/"]COPY ["src/AliasGenerators/AliasGenerators.csproj", "src/AliasGenerators/"]COPY ["src/Utilities/FaviconExtractor/FaviconExtractor.csproj", "src/Utilities/FaviconExtractor/"]RUN dotnet restore "src/AliasVault.WebApp/AliasVault.WebApp.csproj"diff --git a/src/AliasVault.WebApp/Program.cs b/src/AliasVault.WebApp/Program.csindex 1286f3fae..6f1a39b2f 100644--- a/src/AliasVault.WebApp/Program.cs+++ b/src/AliasVault.WebApp/Program.cs@@ -15,7 +15,6 @@ using Microsoft.AspNetCore.Components.Authorization;using Microsoft.AspNetCore.Components.Web;using Microsoft.AspNetCore.Components.WebAssembly.Hosting;using Microsoft.EntityFrameworkCore;-using SqliteWasm;var builder = WebAssemblyHostBuilder.CreateDefault(args);diff --git a/src/AliasVault.WebApp/Services/AliasClientDbService.cs b/src/AliasVault.WebApp/Services/AliasClientDbService.csindex 6cf1b19e9..e88d9b265 100644--- a/src/AliasVault.WebApp/Services/AliasClientDbService.cs+++ b/src/AliasVault.WebApp/Services/AliasClientDbService.cs@@ -5,6 +5,8 @@// </copyright>//-----------------------------------------------------------------------+using System.Data;+namespace AliasVault.WebApp.Services;using System.Net.Http.Json;@@ -23,11 +25,11 @@ using Microsoft.JSInterop;/// </summary>public class AliasClientDbService{+ private readonly AuthService _authService;+ private readonly IJSRuntime _jsRuntime;+ private readonly HttpClient _httpClient;+ private readonly NavigationManager _navigationManager;private AliasClientDbContext? _dbContext;- private AuthService _authService;- private IJSRuntime _jsRuntime;- private HttpClient _httpClient;- private NavigationManager _navigationManager;private Task _initializationTask;private bool _isSuccessfullyInitialized = false;private int _retryCount = 0;@@ -66,7 +68,7 @@ public class AliasClientDbServicepublic async Task<AliasClientDbContext> GetDbContextAsync(){await EnsureInitializedAsync();- if (_isSuccessfullyInitialized == false)+ if (!_isSuccessfullyInitialized){// Retry initialization up to 5 times before giving up.if (_retryCount < 5)@@ -78,7 +80,7 @@ public class AliasClientDbService}else{- throw new Exception("Failed to initialize database.");+ throw new DataException("Failed to initialize database.");}}@@ -99,7 +101,7 @@ public class AliasClientDbServiceusing var command = connection.CreateCommand();command.CommandText = "VACUUM main INTO @fileName";- var tempFileName = Path.GetTempFileName();+ var tempFileName = Path.GetRandomFileName();command.Parameters.Add(new SqliteParameter("@fileName", tempFileName));await command.ExecuteNonQueryAsync();@@ -137,10 +139,6 @@ public class AliasClientDbService{// Create a new in-memory database.string connectionString = "Data Source=AliasClientDb.sqlite";-- // TODO: why doesn't :memory: work? Is the file above still secure?-- // string connectionString = "Data Source=:memory:";using var connection = new SqliteConnection(connectionString);await connection.OpenAsync();@@ -241,7 +239,7 @@ public class AliasClientDbServiceprivate async Task ImportDbContextFromBase64Async(AliasClientDbContext dbContext, string base64String){var bytes = Convert.FromBase64String(base64String);- var tempFileName = Path.GetTempFileName();+ var tempFileName = Path.GetRandomFileName();await File.WriteAllBytesAsync(tempFileName, bytes);using (var connection = new SqliteConnection(dbContext.Database.GetDbConnection().ConnectionString))diff --git a/src/AliasVault.WebApp/_Imports.razor b/src/AliasVault.WebApp/_Imports.razorindex 461ec2c12..3b0f46fa9 100644--- a/src/AliasVault.WebApp/_Imports.razor+++ b/src/AliasVault.WebApp/_Imports.razor@@ -20,6 +20,5 @@@using Microsoft.AspNetCore.Components.Authorization@using Microsoft.AspNetCore.Components.WebAssembly.Authentication@using Blazored.LocalStorage-@using SqliteWasm@using AliasClientDb@using Microsoft.EntityFrameworkCorediff --git a/src/Tests/AliasVault.E2ETests/Common/PlaywrightTest.cs b/src/Tests/AliasVault.E2ETests/Common/PlaywrightTest.csindex f7f2b6b5e..9cf366273 100644--- a/src/Tests/AliasVault.E2ETests/Common/PlaywrightTest.cs+++ b/src/Tests/AliasVault.E2ETests/Common/PlaywrightTest.cs@@ -122,7 +122,7 @@ public class PlaywrightTest/// </summary>/// <param name="relativeUrl">Relative URL.</param>/// <returns>Task.</returns>- public async Task NavigateUsingBlazorRouter(string relativeUrl)+ protected async Task NavigateUsingBlazorRouter(string relativeUrl){// Navigate to the app's base URL initially if not already thereif (!Page.Url.StartsWith(AppBaseUrl))diff --git a/src/Utilities/SqliteWasm/Extensions.cs b/src/Utilities/SqliteWasm/Extensions.csdeleted file mode 100644index cea070b9e..000000000--- a/src/Utilities/SqliteWasm/Extensions.cs+++ /dev/null@@ -1,72 +0,0 @@-using Microsoft.EntityFrameworkCore;-using Microsoft.Extensions.DependencyInjection;-using Microsoft.Extensions.DependencyInjection.Extensions;--namespace SqliteWasm;--/// <summary>-/// Extensions for ease of use.-/// </summary>-public static class Extensions-{- /// <summary>- /// Add helper factory.- /// </summary>- /// <typeparam name="TContext">The <see cref="DbContext"/> being wrapped.</typeparam>- /// <param name="serviceCollection">The <see cref="IServiceCollection"/>.</param>- /// <param name="optionsAction">An action used to configure <see cref="DbContextOptions{TContext}"/>.- /// </param>- /// <param name="lifetime">Lifetime of the service.</param>- /// <returns>The service implementation.</returns>- public static IServiceCollection AddSqliteWasmDbContextFactory<TContext>(- this IServiceCollection serviceCollection,- Action<DbContextOptionsBuilder>? optionsAction = null,- ServiceLifetime lifetime = ServiceLifetime.Singleton)- where TContext : DbContext- => AddSqliteWasmDbContextFactory<TContext>(- serviceCollection,- optionsAction == null ? null : (_, oa) => optionsAction(oa),- lifetime);-- /// <summary>- /// Add helper factory.- /// </summary>- /// <typeparam name="TContext">The <see cref="DbContext"/> being wrapped.</typeparam>- /// <param name="serviceCollection">The <see cref="IServiceCollection"/>.</param>- /// <param name="optionsAction">An action used to configure <see cref="DbContextOptions{TContext}"/>.- /// </param>- /// <param name="lifetime">Lifetime of the service.</param>- /// <returns>The service implementation.</returns>- public static IServiceCollection AddSqliteWasmDbContextFactory<TContext>(- this IServiceCollection serviceCollection,- Action<IServiceProvider, DbContextOptionsBuilder>? optionsAction,- ServiceLifetime lifetime = ServiceLifetime.Singleton)- where TContext : DbContext- {- /*serviceCollection.TryAdd(- new ServiceDescriptor(- typeof(IBrowserCache),- typeof(BrowserCache),- ServiceLifetime.Singleton));-- serviceCollection.TryAdd(- new ServiceDescriptor(- typeof(ISqliteSwap),- typeof(SqliteSwap),- ServiceLifetime.Singleton));- */-- serviceCollection.TryAdd(- new ServiceDescriptor(- typeof(SqliteWasmDbContextFactory<TContext>),- typeof(SqliteWasmDbContextFactory<TContext>),- ServiceLifetime.Singleton));-- serviceCollection.AddDbContextFactory<TContext>(- optionsAction ?? ((s, p) => { }), lifetime);-- //serviceCollection.AddSingleton<IMigration>(migration ?? new(false));-- return serviceCollection;- }-}diff --git a/src/Utilities/SqliteWasm/SqliteWasm.csproj b/src/Utilities/SqliteWasm/SqliteWasm.csprojdeleted file mode 100644index 44e72c612..000000000--- a/src/Utilities/SqliteWasm/SqliteWasm.csproj+++ /dev/null@@ -1,20 +0,0 @@-<Project Sdk="Microsoft.NET.Sdk">-- <PropertyGroup>- <TargetFramework>net8.0</TargetFramework>- <ImplicitUsings>enable</ImplicitUsings>- <Nullable>enable</Nullable>- </PropertyGroup>-- <ItemGroup>- <PackageReference Include="Microsoft.Data.Sqlite" Version="8.0.6" />- <PackageReference Include="Microsoft.EntityFrameworkCore" Version="8.0.6" />- <PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="8.0.6">- <PrivateAssets>all</PrivateAssets>- <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>- </PackageReference>- <PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="8.0.6" />- <PackageReference Include="SQLitePCLRaw.bundle_e_sqlite3" Version="2.1.8" />- </ItemGroup>--</Project>diff --git a/src/Utilities/SqliteWasm/SqliteWasmDbContextFactory.cs b/src/Utilities/SqliteWasm/SqliteWasmDbContextFactory.csdeleted file mode 100644index 8c15977bd..000000000--- a/src/Utilities/SqliteWasm/SqliteWasmDbContextFactory.cs+++ /dev/null@@ -1,130 +0,0 @@-using Microsoft.Data.Sqlite;--namespace SqliteWasm;--using Microsoft.EntityFrameworkCore;--/// <summary>-/// SqliteWasm DbContextFactory implementation.-/// </summary>-/// <typeparam name="TContext">The <see cref="DbContext"/>.</typeparam>-public class SqliteWasmDbContextFactory<TContext>- where TContext : DbContext-{- private readonly IDbContextFactory<TContext> _dbContextFactory;- private static SqliteConnection _sharedConnection;-- /// <summary>- /// Gets or sets whether database has initialized already.- /// </summary>- private bool _initialized = false;-- /// <summary>- /// Initializes a new instance of the <see cref="SqliteWasmDbContextFactory{TContext}"/> class.- /// </summary>- /// <param name="dbContextFactory">The EF Core-provided factory.</param>- public SqliteWasmDbContextFactory(- IDbContextFactory<TContext> dbContextFactory)- {- _dbContextFactory = dbContextFactory;- EnsureSharedConnection();- }-- /// <summary>- /// Create a new <see cref="DbContext"/>.- /// </summary>- /// <returns>The new instance.</returns>- public async Task<TContext> CreateDbContextAsync()- {- var context = await _dbContextFactory.CreateDbContextAsync();-- if (!_initialized)- {- // First time, it should be created.- await context.Database.EnsureCreatedAsync();- // MigrateAsync() undefined??- // await context.Database.MigrateAsync();-- _initialized = true;- }-- // Hook into saved changes.- context.SavedChanges += (o, e) => Context_SavedChanges(context, e);-- return context;-- // Decrypt the database file/binary string- //string encryptedBase64String = "your_encrypted_base64_string_here";- //byte[] encryptedBytes = Convert.FromBase64String(encryptedBase64String);- //byte[] decryptedBytes = Decrypt(encryptedBytes, EncryptionKey);-- // Create an in-memory SQLite database and load the decrypted data- string connectionString = "Data Source=:memory:";- using var connection = new SqliteConnection(connectionString);- connection.Open();- //LoadDatabase(connection, decryptedBytes);-- var options = new DbContextOptionsBuilder<TContext>()- .UseSqlite(connection)- .Options;-- // Grab the context.- //var context = await _dbContextFactory.CreateDbContextAsync();-- if (!_initialized)- {- Console.WriteLine("Initializing database...");- Console.WriteLine(context);- // First time, it should be created.- //await context.Database.EnsureCreatedAsync();- await context.Database.MigrateAsync(); // Uncomment if you have migrations-- _initialized = true;- }-- // Hook into saved changes.- context.SavedChanges += (o, e) => Context_SavedChanges(context, e);-- return context;-- // Grab the context.- /*var context = await _dbContextFactory.CreateDbContextAsync();-- if (!_initialized)- {- // First time, it should be created.- await context.Database.EnsureCreatedAsync();- // MigrateAsync() undefined??- // await context.Database.MigrateAsync();-- _initialized = true;- }-- // Hook into saved changes.- context.SavedChanges += (o, e) => Context_SavedChanges(context, e);-- return context;*/- }-- /// <summary>- /// Ensure the shared connection is created.- /// </summary>- private static void EnsureSharedConnection()- {- if (_sharedConnection == null)- {- _sharedConnection = new SqliteConnection("Data Source=:memory:;");- _sharedConnection.Open();- }- }-- /// <summary>- /// Hook called when the DbContext SaveChanges() has been called.- /// </summary>- /// <param name="ctx"></param>- /// <param name="e"></param>- private async void Context_SavedChanges(TContext ctx, SavedChangesEventArgs e)- {- Console.WriteLine("DbContext SavedChanged called.");- }-}