Privacy-first password manager with built-in email aliasing. Fully encrypted and self-hostable.
Remove obsolete interfaces and shared projects (#2439)
Leendert de Borst94163a79240f
diff --git a/.github/workflows/docker-build.yml b/.github/workflows/docker-build.ymlindex 81eaf0eab..f3e6907c0 100644--- a/.github/workflows/docker-build.yml+++ b/.github/workflows/docker-build.yml@@ -218,7 +218,7 @@ jobs:command: |sleep 15declare -A endpoints=(- ["WASM"]="https://localhost:443"+ ["Client"]="https://localhost:443"["WebApi"]="https://localhost:443/api"["Admin"]="https://localhost:443/admin/user/login")diff --git a/apps/server/AliasVault.Api/Controllers/V1/AuthController.cs b/apps/server/AliasVault.Api/Controllers/V1/AuthController.csindex 391c0a40f..a9bdca953 100644--- a/apps/server/AliasVault.Api/Controllers/V1/AuthController.cs+++ b/apps/server/AliasVault.Api/Controllers/V1/AuthController.cs@@ -22,7 +22,6 @@ using AliasVault.Shared.Models.Enums;using AliasVault.Shared.Models.WebApi;using AliasVault.Shared.Models.WebApi.V1.Auth;using AliasVault.Shared.Models.WebApi.V1.PasswordChange;-using AliasVault.Shared.Providers.Time;using AliasVault.Shared.Server.Services;using AliasVault.Shared.Server.Utilities;using Asp.Versioning;@@ -41,7 +40,7 @@ using SecureRemotePassword;/// <param name="userManager">UserManager instance.</param>/// <param name="configuration">IConfiguration instance.</param>/// <param name="cache">IMemoryCache instance for persisting SRP values during multistep login process.</param>-/// <param name="timeProvider">ITimeProvider instance. This returns the time which can be mutated for testing.</param>+/// <param name="timeProvider">TimeProvider instance.</param>/// <param name="authLoggingService">AuthLoggingService instance. This is used to log auth attempts to the database.</param>/// <param name="config">Config instance.</param>/// <param name="settingsService">ServerSettingsService instance.</param>@@ -49,7 +48,7 @@ using SecureRemotePassword;[Route("v{version:apiVersion}/[controller]")][ApiController][ApiVersion("1")]-public class AuthController(IAliasServerDbContextFactory dbContextFactory, UserManager<AliasVaultUser> userManager, IConfiguration configuration, IMemoryCache cache, ITimeProvider timeProvider, AuthLoggingService authLoggingService, Config config, ServerSettingsService settingsService, IpBlockListService ipBlockListService) : ControllerBase+public class AuthController(IAliasServerDbContextFactory dbContextFactory, UserManager<AliasVaultUser> userManager, IConfiguration configuration, IMemoryCache cache, TimeProvider timeProvider, AuthLoggingService authLoggingService, Config config, ServerSettingsService settingsService, IpBlockListService ipBlockListService) : ControllerBase{/// <summary>/// Access token validity in minutes.@@ -851,7 +850,7 @@ public class AuthController(IAliasServerDbContextFactory dbContextFactory, UserMissuer: configuration["Jwt:Issuer"] ?? string.Empty,audience: configuration["Jwt:Issuer"] ?? string.Empty,claims: claims,- expires: timeProvider.UtcNow.AddSeconds(AccessTokenValiditySeconds),+ expires: timeProvider.GetUtcNow().UtcDateTime.AddSeconds(AccessTokenValiditySeconds),signingCredentials: credentials);return new JwtSecurityTokenHandler().WriteToken(token);@@ -901,7 +900,7 @@ public class AuthController(IAliasServerDbContextFactory dbContextFactory, UserM// Token reuse window:// Check if a new refresh token was already generated for the current token in the last 30 seconds.// If yes, then return the already generated new token. This is to prevent client-side race conditions.- var existingTokenReuseWindow = timeProvider.UtcNow.AddSeconds(-30);+ var existingTokenReuseWindow = timeProvider.GetUtcNow().UtcDateTime.AddSeconds(-30);var existingTokenReuse = await context.AliasVaultUserRefreshTokens.FirstOrDefaultAsync(t => t.UserId == user.Id &&t.PreviousTokenValue == existingTokenValue &&@@ -917,7 +916,7 @@ public class AuthController(IAliasServerDbContextFactory dbContextFactory, UserM// Check if the refresh token still exists and is not expired.var existingToken = await context.AliasVaultUserRefreshTokens.FirstOrDefaultAsync(t => t.UserId == user.Id && t.Value == existingTokenValue);- if (existingToken == null || existingToken.ExpireDate < timeProvider.UtcNow)+ if (existingToken == null || existingToken.ExpireDate < timeProvider.GetUtcNow().UtcDateTime){return null;}@@ -967,8 +966,8 @@ public class AuthController(IAliasServerDbContextFactory dbContextFactory, UserMIpAddress = IpAddressUtility.GetAnonymizedIpFromContext(HttpContext, config.IpLoggingEnabled),Value = refreshToken,PreviousTokenValue = existingTokenValue,- ExpireDate = timeProvider.UtcNow.Add(newTokenLifetime),- CreatedAt = timeProvider.UtcNow,+ ExpireDate = timeProvider.GetUtcNow().UtcDateTime.Add(newTokenLifetime),+ CreatedAt = timeProvider.GetUtcNow().UtcDateTime,});await context.SaveChangesAsync();diff --git a/apps/server/AliasVault.Api/Controllers/V1/VaultController.cs b/apps/server/AliasVault.Api/Controllers/V1/VaultController.csindex a3ad7d639..8ad5c90ef 100644--- a/apps/server/AliasVault.Api/Controllers/V1/VaultController.cs+++ b/apps/server/AliasVault.Api/Controllers/V1/VaultController.cs@@ -20,7 +20,6 @@ using AliasVault.Shared.Models.Enums;using AliasVault.Shared.Models.WebApi;using AliasVault.Shared.Models.WebApi.V1.PasswordChange;using AliasVault.Shared.Models.WebApi.V1.Vault;-using AliasVault.Shared.Providers.Time;using AliasVault.Shared.Server.Services;using Asp.Versioning;using Microsoft.AspNetCore.Identity;@@ -34,13 +33,13 @@ using Microsoft.Extensions.Caching.Memory;/// <param name="logger">ILogger instance.</param>/// <param name="dbContextFactory">DbContext instance.</param>/// <param name="userManager">UserManager instance.</param>-/// <param name="timeProvider">ITimeProvider instance.</param>+/// <param name="timeProvider">TimeProvider instance.</param>/// <param name="authLoggingService">AuthLoggingService instance.</param>/// <param name="cache">IMemoryCache instance.</param>/// <param name="config">Config instance.</param>/// <param name="rateLimitService">RateLimitService instance.</param>[ApiVersion("1")]-public class VaultController(ILogger<VaultController> logger, IAliasServerDbContextFactory dbContextFactory, UserManager<AliasVaultUser> userManager, ITimeProvider timeProvider, AuthLoggingService authLoggingService, IMemoryCache cache, Config config, RateLimitService rateLimitService) : AuthenticatedRequestController(userManager)+public class VaultController(ILogger<VaultController> logger, IAliasServerDbContextFactory dbContextFactory, UserManager<AliasVaultUser> userManager, TimeProvider timeProvider, AuthLoggingService authLoggingService, IMemoryCache cache, Config config, RateLimitService rateLimitService) : AuthenticatedRequestController(userManager){/// <summary>/// Default retention policy for vaults.@@ -191,8 +190,8 @@ public class VaultController(ILogger<VaultController> logger, IAliasServerDbContcurrentManifest.EmailClaimsCount = model.EmailAddressList.Count;currentManifest.Client = ClientHeader;currentManifest.UpdatedByUserId = user.Id;- currentManifest.CreatedAt = timeProvider.UtcNow;- currentManifest.UpdatedAt = timeProvider.UtcNow;+ currentManifest.CreatedAt = timeProvider.GetUtcNow().UtcDateTime;+ currentManifest.UpdatedAt = timeProvider.GetUtcNow().UtcDateTime;// Run the vault retention manager to clean up old history revisions, then commit to database.await ApplyVaultRetention(context, currentManifest, archivedRevision);@@ -293,15 +292,15 @@ public class VaultController(ILogger<VaultController> logger, IAliasServerDbContcurrentManifest.EncryptionSettings = Defaults.EncryptionSettings;currentManifest.Client = ClientHeader;currentManifest.UpdatedByUserId = user.Id;- currentManifest.CreatedAt = timeProvider.UtcNow;- currentManifest.UpdatedAt = timeProvider.UtcNow;+ currentManifest.CreatedAt = timeProvider.GetUtcNow().UtcDateTime;+ currentManifest.UpdatedAt = timeProvider.GetUtcNow().UtcDateTime;// Run the vault retention manager to clean up old history revisions, then commit to database.await ApplyVaultRetention(context, currentManifest, archivedRevision);await context.SaveChangesAsync();// Update the password last changed at timestamp for user.- user.PasswordChangedAt = timeProvider.UtcNow;+ user.PasswordChangedAt = timeProvider.GetUtcNow().UtcDateTime;await GetUserManager().UpdateAsync(user);await authLoggingService.LogAuthEventSuccessAsync(user.UserName!, AuthEventType.PasswordChange);@@ -388,7 +387,7 @@ public class VaultController(ILogger<VaultController> logger, IAliasServerDbConthistoryRevisions.Add(justArchived);}- var revisionsToDelete = VaultRetentionManager.ApplyRetention(_retentionPolicy, historyRevisions, timeProvider.UtcNow, currentManifest);+ var revisionsToDelete = VaultRetentionManager.ApplyRetention(_retentionPolicy, historyRevisions, timeProvider.GetUtcNow().UtcDateTime, currentManifest);context.VaultManifestsHistory.RemoveRange(revisionsToDelete);// Blob references of pruned revisions are deleted explicitly (they only cascade with the whole manifest).@@ -444,7 +443,7 @@ public class VaultController(ILogger<VaultController> logger, IAliasServerDbContelse{// Time-based cap: aliases created within the rolling window (create-then-delete still counts).- var windowStart = timeProvider.UtcNow.AddSeconds(-limit.WindowSeconds);+ var windowStart = timeProvider.GetUtcNow().UtcDateTime.AddSeconds(-limit.WindowSeconds);baseCount = await context.EmailClaimLinks.Where(l => l.EmailClaim.CreatedAt >= windowStart && l.VaultManifest.OwnerGroupId == user.PersonalGroupId).Select(l => l.EmailClaimId).Distinct().CountAsync();}@@ -488,7 +487,7 @@ public class VaultController(ILogger<VaultController> logger, IAliasServerDbContif (personalLink is { State: EmailClaimLinkState.Removed }){personalLink.State = EmailClaimLinkState.Active;- existingUserClaim.UpdatedAt = timeProvider.UtcNow;+ existingUserClaim.UpdatedAt = timeProvider.GetUtcNow().UtcDateTime;}// Reviving the link is all there is to re-enabling the alias: a claim counts as live for as long as@@ -526,8 +525,8 @@ public class VaultController(ILogger<VaultController> logger, IAliasServerDbContAddress = sanitizedEmail,AddressLocal = sanitizedEmail.Split('@')[0],AddressDomain = sanitizedEmail.Split('@')[1],- CreatedAt = timeProvider.UtcNow,- UpdatedAt = timeProvider.UtcNow,+ CreatedAt = timeProvider.GetUtcNow().UtcDateTime,+ UpdatedAt = timeProvider.GetUtcNow().UtcDateTime,});addedThisSync++;}@@ -558,7 +557,7 @@ public class VaultController(ILogger<VaultController> logger, IAliasServerDbContlink.State = EmailClaimLinkState.Removed;}- existingClaim.UpdatedAt = timeProvider.UtcNow;+ existingClaim.UpdatedAt = timeProvider.GetUtcNow().UtcDateTime;}await context.SaveChangesAsync();@@ -590,7 +589,7 @@ public class VaultController(ILogger<VaultController> logger, IAliasServerDbContforeach (var key in otherKeys){key.IsPrimary = false;- key.UpdatedAt = timeProvider.UtcNow;+ key.UpdatedAt = timeProvider.GetUtcNow().UtcDateTime;}// Check if the new public key already exists but is not marked as primary.@@ -599,7 +598,7 @@ public class VaultController(ILogger<VaultController> logger, IAliasServerDbCont{// Set the existing key to be primary.existingPublicKey.IsPrimary = true;- existingPublicKey.UpdatedAt = timeProvider.UtcNow;+ existingPublicKey.UpdatedAt = timeProvider.GetUtcNow().UtcDateTime;await context.SaveChangesAsync();return;}@@ -611,8 +610,8 @@ public class VaultController(ILogger<VaultController> logger, IAliasServerDbContAlgorithm = VaultKeyAlgorithm.RsaOaepSha256,PublicKey = newPublicKey,IsPrimary = true,- CreatedAt = timeProvider.UtcNow,- UpdatedAt = timeProvider.UtcNow,+ CreatedAt = timeProvider.GetUtcNow().UtcDateTime,+ UpdatedAt = timeProvider.GetUtcNow().UtcDateTime,};context.VaultManifestDeliveryKeys.Add(newPublicKeyEntry);diff --git a/apps/server/AliasVault.Api/Controllers/V2/AuthController.cs b/apps/server/AliasVault.Api/Controllers/V2/AuthController.csindex c63985016..09dbd0ac4 100644--- a/apps/server/AliasVault.Api/Controllers/V2/AuthController.cs+++ b/apps/server/AliasVault.Api/Controllers/V2/AuthController.cs@@ -23,7 +23,6 @@ using AliasVault.Shared;using AliasVault.Shared.Models.Enums;using AliasVault.Shared.Models.WebApi;using AliasVault.Shared.Models.WebApi.V2.Auth;-using AliasVault.Shared.Providers.Time;using AliasVault.Shared.Server.Services;using AliasVault.Shared.Server.Utilities;using Asp.Versioning;@@ -42,7 +41,7 @@ using SecureRemotePassword;/// <param name="userManager">UserManager instance.</param>/// <param name="configuration">IConfiguration instance.</param>/// <param name="cache">IMemoryCache instance for persisting SRP values during multistep login process.</param>-/// <param name="timeProvider">ITimeProvider instance. This returns the time which can be mutated for testing.</param>+/// <param name="timeProvider">TimeProvider instance.</param>/// <param name="authLoggingService">AuthLoggingService instance. This is used to log auth attempts to the database.</param>/// <param name="config">Config instance.</param>/// <param name="settingsService">ServerSettingsService instance.</param>@@ -52,7 +51,7 @@ using SecureRemotePassword;[Route("v{version:apiVersion}/[controller]")][ApiController][ApiVersion("2")]-public class AuthController(IAliasServerDbContextFactory dbContextFactory, UserManager<AliasVaultUser> userManager, IConfiguration configuration, IMemoryCache cache, ITimeProvider timeProvider, AuthLoggingService authLoggingService, Config config, ServerSettingsService settingsService, RegistrationRateLimitService registrationRateLimitService, IpBlockListService ipBlockListService, MobileLoginRateLimitService mobileLoginRateLimitService) : ControllerBase+public class AuthController(IAliasServerDbContextFactory dbContextFactory, UserManager<AliasVaultUser> userManager, IConfiguration configuration, IMemoryCache cache, TimeProvider timeProvider, AuthLoggingService authLoggingService, Config config, ServerSettingsService settingsService, RegistrationRateLimitService registrationRateLimitService, IpBlockListService ipBlockListService, MobileLoginRateLimitService mobileLoginRateLimitService) : ControllerBase{/// <summary>/// Access token validity in minutes.@@ -435,15 +434,15 @@ public class AuthController(IAliasServerDbContextFactory dbContextFactory, UserM{UserName = UsernameHelper.NormalizeUsername(model.Username),SrpIdentity = AuthHelper.ResolveSrpIdentity(model.SrpIdentity, model.Username),- CreatedAt = timeProvider.UtcNow,- UpdatedAt = timeProvider.UtcNow,- PasswordChangedAt = timeProvider.UtcNow,+ CreatedAt = timeProvider.GetUtcNow().UtcDateTime,+ UpdatedAt = timeProvider.GetUtcNow().UtcDateTime,+ PasswordChangedAt = timeProvider.GetUtcNow().UtcDateTime,};var personalManifestId = Guid.NewGuid();// Create the personal group before the user row.- var personalGroup = GroupHelper.CreatePersonalGroup(user, timeProvider.UtcNow);+ var personalGroup = GroupHelper.CreatePersonalGroup(user, timeProvider.GetUtcNow().UtcDateTime);await using (var context = await dbContextFactory.CreateDbContextAsync()){context.Groups.Add(personalGroup);@@ -457,7 +456,7 @@ public class AuthController(IAliasServerDbContextFactory dbContextFactory, UserM// Create the owner membership and personal manifest.await using (var context = await dbContextFactory.CreateDbContextAsync()){- context.GroupMembers.Add(GroupHelper.CreateOwnerMembership(personalGroup, user.Id, timeProvider.UtcNow));+ context.GroupMembers.Add(GroupHelper.CreateOwnerMembership(personalGroup, user.Id, timeProvider.GetUtcNow().UtcDateTime));// Create placeholder manifest for the account which is empty and will be replaced by the first real manifest push by the client.context.VaultManifests.Add(new AliasServerDb.VaultManifest@@ -472,8 +471,8 @@ public class AuthController(IAliasServerDbContextFactory dbContextFactory, UserMEncryptionType = null,EncryptionSettings = null,FileSize = 0,- CreatedAt = timeProvider.UtcNow,- UpdatedAt = timeProvider.UtcNow,+ CreatedAt = timeProvider.GetUtcNow().UtcDateTime,+ UpdatedAt = timeProvider.GetUtcNow().UtcDateTime,});context.UserUnlockKeys.Add(new UserUnlockKey@@ -490,8 +489,8 @@ public class AuthController(IAliasServerDbContextFactory dbContextFactory, UserMEncryptionType = model.EncryptionType,EncryptionSettings = model.EncryptionSettings,}.ToJson(),- CreatedAt = timeProvider.UtcNow,- UpdatedAt = timeProvider.UtcNow,+ CreatedAt = timeProvider.GetUtcNow().UtcDateTime,+ UpdatedAt = timeProvider.GetUtcNow().UtcDateTime,});context.UserGrantKeys.Add(new UserGrantKey@@ -502,8 +501,8 @@ public class AuthController(IAliasServerDbContextFactory dbContextFactory, UserMPublicKey = model.AccountPublicKey!,EncryptedPrivateKey = model.EncryptedAccountPrivateKey!,IsPrimary = true,- CreatedAt = timeProvider.UtcNow,- UpdatedAt = timeProvider.UtcNow,+ CreatedAt = timeProvider.GetUtcNow().UtcDateTime,+ UpdatedAt = timeProvider.GetUtcNow().UtcDateTime,});context.VaultManifestAccessKeys.Add(new VaultManifestAccessKey@@ -515,8 +514,8 @@ public class AuthController(IAliasServerDbContextFactory dbContextFactory, UserMAlgorithm = VaultKeyAlgorithm.Aes256Gcm,EncryptedVek = model.EncryptedVek!,AccountKeyVersion = 0,- CreatedAt = timeProvider.UtcNow,- UpdatedAt = timeProvider.UtcNow,+ CreatedAt = timeProvider.GetUtcNow().UtcDateTime,+ UpdatedAt = timeProvider.GetUtcNow().UtcDateTime,});await context.SaveChangesAsync();@@ -614,7 +613,7 @@ public class AuthController(IAliasServerDbContextFactory dbContextFactory, UserMreturn BadRequest(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.PASSWORD_MISMATCH, 400));}- var now = timeProvider.UtcNow;+ var now = timeProvider.GetUtcNow().UtcDateTime;var settings = await settingsService.GetAllSettingsAsync();var deviceIdentifier = AuthHelper.GenerateDeviceIdentifier(Request);@@ -779,7 +778,7 @@ public class AuthController(IAliasServerDbContextFactory dbContextFactory, UserMId = requestId,ClientPublicKey = model.ClientPublicKey,PollSecretHash = MobileLoginRequestHelper.HashPollSecret(pollSecret),- CreatedAt = timeProvider.UtcNow,+ CreatedAt = timeProvider.GetUtcNow().UtcDateTime,ClientIpAddress = ipAddress,ClientName = MobileLoginRequestHelper.SanitizeClientName(ClientHeaderInfo.GetRawValue(Request)),ClientBrowser = RequestClientInfo.DetermineBrowser(HttpContext),@@ -822,7 +821,7 @@ public class AuthController(IAliasServerDbContextFactory dbContextFactory, UserMif (loginRequest.FulfilledAt == null){- if (MobileLoginRequestHelper.IsApprovalWindowClosed(loginRequest, timeProvider.UtcNow))+ if (MobileLoginRequestHelper.IsApprovalWindowClosed(loginRequest, timeProvider.GetUtcNow().UtcDateTime)){return NotFound(ApiErrorCodeHelper.CreateErrorResponse(ApiErrorCode.MOBILE_LOGIN_REQUEST_NOT_FOUND, 404));}@@ -831,7 +830,7 @@ public class AuthController(IAliasServerDbContextFactory dbContextFactory, UserM}// One-time use: an approved request is handed out once, and only shortly after the approval.- if (loginRequest.RetrievedAt != null || loginRequest.EncryptedUnlockKey == null || MobileLoginRequestHelper.IsRetrievalWindowClosed(loginRequest, timeProvider.UtcNow))+ if (loginRequest.RetrievedAt != null || loginRequest.EncryptedUnlockKey == null || MobileLoginRequestHelper.IsRetrievalWindowClosed(loginRequest, timeProvider.GetUtcNow().UtcDateTime)){return NotFound(ApiErrorCodeHelper.CreateErrorResponse(ApiErrorCode.MOBILE_LOGIN_REQUEST_NOT_FOUND, 404));}@@ -861,7 +860,7 @@ public class AuthController(IAliasServerDbContextFactory dbContextFactory, UserM// Claim the request and clear its key material in one transaction.var clientPublicKey = loginRequest.ClientPublicKey;var encryptedUnlockKey = loginRequest.EncryptedUnlockKey;- var retrievedAt = timeProvider.UtcNow;+ var retrievedAt = timeProvider.GetUtcNow().UtcDateTime;var claimed = await context.MobileLoginRequests.Where(r => r.Id == loginRequest.Id && r.RetrievedAt == null).ExecuteUpdateAsync(u => u.SetProperty(r => r.RetrievedAt, retrievedAt).SetProperty(r => r.ClientPublicKey, string.Empty).SetProperty(r => r.EncryptedUnlockKey, (string?)null));@@ -911,7 +910,7 @@ public class AuthController(IAliasServerDbContextFactory dbContextFactory, UserMawait using var context = await dbContextFactory.CreateDbContextAsync();var loginRequest = await context.MobileLoginRequests.FirstOrDefaultAsync(r => r.Id == model.RequestId);- if (loginRequest == null || !MobileLoginRequestHelper.IsAwaitingApproval(loginRequest, timeProvider.UtcNow))+ if (loginRequest == null || !MobileLoginRequestHelper.IsAwaitingApproval(loginRequest, timeProvider.GetUtcNow().UtcDateTime)){return NotFound(ApiErrorCodeHelper.CreateErrorResponse(ApiErrorCode.MOBILE_LOGIN_REQUEST_NOT_FOUND, 404));}@@ -947,7 +946,7 @@ public class AuthController(IAliasServerDbContextFactory dbContextFactory, UserM}var loginRequest = await context.MobileLoginRequests.FirstOrDefaultAsync(r => r.Id == model.RequestId);- if (loginRequest == null || loginRequest.DeclinedAt != null || MobileLoginRequestHelper.IsApprovalWindowClosed(loginRequest, timeProvider.UtcNow))+ if (loginRequest == null || loginRequest.DeclinedAt != null || MobileLoginRequestHelper.IsApprovalWindowClosed(loginRequest, timeProvider.GetUtcNow().UtcDateTime)){return NotFound(ApiErrorCodeHelper.CreateErrorResponse(ApiErrorCode.MOBILE_LOGIN_REQUEST_NOT_FOUND, 404));}@@ -959,7 +958,7 @@ public class AuthController(IAliasServerDbContextFactory dbContextFactory, UserM}// Store the answer in one transaction.- var fulfilledAt = timeProvider.UtcNow;+ var fulfilledAt = timeProvider.GetUtcNow().UtcDateTime;var mobileIpAddress = IpAddressUtility.GetAnonymizedIpFromContext(HttpContext, config.IpLoggingEnabled);var updated = await context.MobileLoginRequests.Where(r => r.Id == loginRequest.Id && r.FulfilledAt == null && r.DeclinedAt == null)@@ -990,14 +989,14 @@ public class AuthController(IAliasServerDbContextFactory dbContextFactory, UserM}var loginRequest = await context.MobileLoginRequests.FirstOrDefaultAsync(r => r.Id == model.RequestId);- if (loginRequest == null || !MobileLoginRequestHelper.IsAwaitingApproval(loginRequest, timeProvider.UtcNow))+ if (loginRequest == null || !MobileLoginRequestHelper.IsAwaitingApproval(loginRequest, timeProvider.GetUtcNow().UtcDateTime)){return NotFound(ApiErrorCodeHelper.CreateErrorResponse(ApiErrorCode.MOBILE_LOGIN_REQUEST_NOT_FOUND, 404));}loginRequest.ClientPublicKey = string.Empty;loginRequest.UserId = user.Id;- loginRequest.DeclinedAt = timeProvider.UtcNow;+ loginRequest.DeclinedAt = timeProvider.GetUtcNow().UtcDateTime;loginRequest.MobileIpAddress = IpAddressUtility.GetAnonymizedIpFromContext(HttpContext, config.IpLoggingEnabled);await context.SaveChangesAsync();@@ -1296,7 +1295,7 @@ public class AuthController(IAliasServerDbContextFactory dbContextFactory, UserM}// Record usage of this unlock method for statistics purposes.- await AuthHelper.TouchUnlockKeyLastUsedAsync(context, srpResult.UnlockKeyId, timeProvider.UtcNow);+ await AuthHelper.TouchUnlockKeyLastUsedAsync(context, srpResult.UnlockKeyId, timeProvider.GetUtcNow().UtcDateTime);return (user, srpResult.Session, null);}@@ -1324,7 +1323,7 @@ public class AuthController(IAliasServerDbContextFactory dbContextFactory, UserMissuer: configuration["Jwt:Issuer"] ?? string.Empty,audience: configuration["Jwt:Issuer"] ?? string.Empty,claims: claims,- expires: timeProvider.UtcNow.AddSeconds(AccessTokenValiditySeconds),+ expires: timeProvider.GetUtcNow().UtcDateTime.AddSeconds(AccessTokenValiditySeconds),signingCredentials: credentials);return new JwtSecurityTokenHandler().WriteToken(token);@@ -1374,7 +1373,7 @@ public class AuthController(IAliasServerDbContextFactory dbContextFactory, UserM// Token reuse window:// Check if a new refresh token was already generated for the current token in the last 30 seconds.// If yes, then return the already generated new token. This is to prevent client-side race conditions.- var existingTokenReuseWindow = timeProvider.UtcNow.AddSeconds(-30);+ var existingTokenReuseWindow = timeProvider.GetUtcNow().UtcDateTime.AddSeconds(-30);var existingTokenReuse = await context.AliasVaultUserRefreshTokens.FirstOrDefaultAsync(t => t.UserId == user.Id &&t.PreviousTokenValue == existingTokenValue &&@@ -1390,7 +1389,7 @@ public class AuthController(IAliasServerDbContextFactory dbContextFactory, UserM// Check if the refresh token still exists and is not expired.var existingToken = await context.AliasVaultUserRefreshTokens.FirstOrDefaultAsync(t => t.UserId == user.Id && t.Value == existingTokenValue);- if (existingToken == null || existingToken.ExpireDate < timeProvider.UtcNow)+ if (existingToken == null || existingToken.ExpireDate < timeProvider.GetUtcNow().UtcDateTime){return null;}@@ -1440,8 +1439,8 @@ public class AuthController(IAliasServerDbContextFactory dbContextFactory, UserMIpAddress = IpAddressUtility.GetAnonymizedIpFromContext(HttpContext, config.IpLoggingEnabled),Value = refreshToken,PreviousTokenValue = existingTokenValue,- ExpireDate = timeProvider.UtcNow.Add(newTokenLifetime),- CreatedAt = timeProvider.UtcNow,+ ExpireDate = timeProvider.GetUtcNow().UtcDateTime.Add(newTokenLifetime),+ CreatedAt = timeProvider.GetUtcNow().UtcDateTime,});await context.SaveChangesAsync();diff --git a/apps/server/AliasVault.Api/Controllers/V2/GroupsController.cs b/apps/server/AliasVault.Api/Controllers/V2/GroupsController.csindex a08e4ac28..d2226fd97 100644--- a/apps/server/AliasVault.Api/Controllers/V2/GroupsController.cs+++ b/apps/server/AliasVault.Api/Controllers/V2/GroupsController.cs@@ -17,7 +17,6 @@ using AliasVault.Shared.Models.Enums;using AliasVault.Shared.Models.WebApi;using AliasVault.Shared.Models.WebApi.V2.Auth;using AliasVault.Shared.Models.WebApi.V2.Groups;-using AliasVault.Shared.Providers.Time;using AliasVault.Shared.Server.Capabilities;using Asp.Versioning;using Microsoft.AspNetCore.Identity;@@ -34,7 +33,7 @@ using Microsoft.Extensions.Caching.Memory;/// <param name="cache">Memory cache holding the server's SRP ephemeral between the delete initiate and confirm calls.</param>/// <param name="authLoggingService">Auth logging service, recording shared manifest creation and the master password checks guarding deletion.</param>[ApiVersion("2")]-public class GroupsController(IAliasServerDbContextFactory dbContextFactory, UserManager<AliasVaultUser> userManager, ITimeProvider timeProvider, IMemoryCache cache, AuthLoggingService authLoggingService) : AuthenticatedRequestController(userManager)+public class GroupsController(IAliasServerDbContextFactory dbContextFactory, UserManager<AliasVaultUser> userManager, TimeProvider timeProvider, IMemoryCache cache, AuthLoggingService authLoggingService) : AuthenticatedRequestController(userManager){/// <summary>/// How many shared manifests one group may hold. TODO: hardcoded for now; make this dynamic when needed.@@ -186,12 +185,12 @@ public class GroupsController(IAliasServerDbContextFactory dbContextFactory, UseRevisionNumber = 0,FileSize = 0,Client = ClientHeader,- CreatedAt = timeProvider.UtcNow,- UpdatedAt = timeProvider.UtcNow,+ CreatedAt = timeProvider.GetUtcNow().UtcDateTime,+ UpdatedAt = timeProvider.GetUtcNow().UtcDateTime,};context.VaultManifests.Add(manifest);- context.VaultManifestShareDetails.Add(new VaultManifestShareDetails { ManifestId = manifest.ManifestId, EncryptedName = model.EncryptedName, CreatedAt = timeProvider.UtcNow, UpdatedAt = timeProvider.UtcNow });- context.VaultManifestAccessKeys.Add(GrantHelper.BuildGrant(manifest.ManifestId, me.Id, selfPublicKeyId.Value, model.SelfEncryptedVek, algorithm, manifest.KeyVersion, timeProvider.UtcNow));+ context.VaultManifestShareDetails.Add(new VaultManifestShareDetails { ManifestId = manifest.ManifestId, EncryptedName = model.EncryptedName, CreatedAt = timeProvider.GetUtcNow().UtcDateTime, UpdatedAt = timeProvider.GetUtcNow().UtcDateTime });+ context.VaultManifestAccessKeys.Add(GrantHelper.BuildGrant(manifest.ManifestId, me.Id, selfPublicKeyId.Value, model.SelfEncryptedVek, algorithm, manifest.KeyVersion, timeProvider.GetUtcNow().UtcDateTime));try{@@ -301,8 +300,8 @@ public class GroupsController(IAliasServerDbContextFactory dbContextFactory, UseUserGrantKeyId = model.Grant.RecipientPublicKeyId,VaultKeyVersion = manifestKeyVersion.Value,Algorithm = algorithm,- CreatedAt = timeProvider.UtcNow,- UpdatedAt = timeProvider.UtcNow,+ CreatedAt = timeProvider.GetUtcNow().UtcDateTime,+ UpdatedAt = timeProvider.GetUtcNow().UtcDateTime,};context.GroupInvitations.Add(invitation);@@ -372,7 +371,7 @@ public class GroupsController(IAliasServerDbContextFactory dbContextFactory, Useif (await GrantHelper.RevokeAccessAsync(context, manifestId, userId)){- await ClientActionHelper.EnqueueForGroupAsync(context, ClientActionType.RotateManifestDeliveryKey, groupId, manifestId, timeProvider.UtcNow);+ await ClientActionHelper.EnqueueForGroupAsync(context, ClientActionType.RotateManifestDeliveryKey, groupId, manifestId, timeProvider.GetUtcNow().UtcDateTime);}await context.SaveChangesAsync();@@ -415,7 +414,7 @@ public class GroupsController(IAliasServerDbContextFactory dbContextFactory, Usevar details = await context.VaultManifestShareDetails.FirstOrDefaultAsync(d => d.ManifestId == manifestId);if (details is null){- details = new VaultManifestShareDetails { ManifestId = manifestId, CreatedAt = timeProvider.UtcNow };+ details = new VaultManifestShareDetails { ManifestId = manifestId, CreatedAt = timeProvider.GetUtcNow().UtcDateTime };context.VaultManifestShareDetails.Add(details);}@@ -424,7 +423,7 @@ public class GroupsController(IAliasServerDbContextFactory dbContextFactory, Usedetails.EncryptedName = model.EncryptedName;}- details.UpdatedAt = timeProvider.UtcNow;+ details.UpdatedAt = timeProvider.GetUtcNow().UtcDateTime;await context.SaveChangesAsync();@@ -597,8 +596,8 @@ public class GroupsController(IAliasServerDbContextFactory dbContextFactory, Use}invitation.State = GroupInvitationState.Accepted;- invitation.RespondedAt = timeProvider.UtcNow;- invitation.UpdatedAt = timeProvider.UtcNow;+ invitation.RespondedAt = timeProvider.GetUtcNow().UtcDateTime;+ invitation.UpdatedAt = timeProvider.GetUtcNow().UtcDateTime;// The encrypted copy has become the grant, so it stops being a second copy of the key lying around.invitation.EncryptedVek = null;@@ -741,8 +740,8 @@ public class GroupsController(IAliasServerDbContextFactory dbContextFactory, Useinvitation.EncryptedVek = null;invitation.EncryptedName = null;invitation.UserGrantKeyId = null;- invitation.RespondedAt = timeProvider.UtcNow;- invitation.UpdatedAt = timeProvider.UtcNow;+ invitation.RespondedAt = timeProvider.GetUtcNow().UtcDateTime;+ invitation.UpdatedAt = timeProvider.GetUtcNow().UtcDateTime;}/// <summary>@@ -766,7 +765,7 @@ public class GroupsController(IAliasServerDbContextFactory dbContextFactory, Usereturn true;}- context.VaultManifestAccessKeys.Add(GrantHelper.BuildGrant(manifestId, userId, invitation.UserGrantKeyId.Value, invitation.EncryptedVek, invitation.Algorithm, keyVersion, timeProvider.UtcNow));+ context.VaultManifestAccessKeys.Add(GrantHelper.BuildGrant(manifestId, userId, invitation.UserGrantKeyId.Value, invitation.EncryptedVek, invitation.Algorithm, keyVersion, timeProvider.GetUtcNow().UtcDateTime));return true;}diff --git a/apps/server/AliasVault.Api/Controllers/V2/VaultController.cs b/apps/server/AliasVault.Api/Controllers/V2/VaultController.csindex 0873c42f6..fc0a67d27 100644--- a/apps/server/AliasVault.Api/Controllers/V2/VaultController.cs+++ b/apps/server/AliasVault.Api/Controllers/V2/VaultController.cs@@ -17,7 +17,6 @@ using AliasVault.Api.Vault.RetentionRules;using AliasVault.Shared.Models.Enums;using AliasVault.Shared.Models.WebApi;using AliasVault.Shared.Models.WebApi.V2.Vault;-using AliasVault.Shared.Providers.Time;using Asp.Versioning;using Microsoft.AspNetCore.Identity;using Microsoft.AspNetCore.Mvc;@@ -39,7 +38,7 @@ public class VaultController(ILogger<VaultController> logger,IAliasServerDbContextFactory dbContextFactory,UserManager<AliasVaultUser> userManager,- ITimeProvider timeProvider,+ TimeProvider timeProvider,Config config,RateLimitService rateLimitService) : AuthenticatedRequestController(userManager){@@ -469,7 +468,7 @@ public class VaultController(row.CredentialsCount = mw.CredentialsCount;row.Client = ClientHeader;row.UpdatedByUserId = user.Id;- row.UpdatedAt = timeProvider.UtcNow;+ row.UpdatedAt = timeProvider.GetUtcNow().UtcDateTime;// Every manifest counts the aliases the push filed against it, shared manifests included. One// address may be pushed for several manifests at once, so count distinct addresses per manifest.@@ -480,7 +479,7 @@ public class VaultController(if (row.OwnerGroupId == user.PersonalGroupId){- row.CreatedAt = timeProvider.UtcNow;+ row.CreatedAt = timeProvider.GetUtcNow().UtcDateTime;// Create the account-key hierarchy atomically with this write on the migration (first push after// the client re-encrypted the vault under a fresh VEK).@@ -500,8 +499,8 @@ public class VaultController(EncryptionType = row.EncryptionType,EncryptionSettings = row.EncryptionSettings,}.ToJson(),- CreatedAt = timeProvider.UtcNow,- UpdatedAt = timeProvider.UtcNow,+ CreatedAt = timeProvider.GetUtcNow().UtcDateTime,+ UpdatedAt = timeProvider.GetUtcNow().UtcDateTime,});context.UserGrantKeys.Add(new UserGrantKey@@ -512,8 +511,8 @@ public class VaultController(PublicKey = accountKeys.AccountPublicKey!,EncryptedPrivateKey = accountKeys.EncryptedAccountPrivateKey!,IsPrimary = true,- CreatedAt = timeProvider.UtcNow,- UpdatedAt = timeProvider.UtcNow,+ CreatedAt = timeProvider.GetUtcNow().UtcDateTime,+ UpdatedAt = timeProvider.GetUtcNow().UtcDateTime,});context.VaultManifestAccessKeys.Add(new VaultManifestAccessKey@@ -525,8 +524,8 @@ public class VaultController(Algorithm = VaultKeyAlgorithm.Aes256Gcm,EncryptedVek = accountKeys.EncryptedVek!,AccountKeyVersion = 0,- CreatedAt = timeProvider.UtcNow,- UpdatedAt = timeProvider.UtcNow,+ CreatedAt = timeProvider.GetUtcNow().UtcDateTime,+ UpdatedAt = timeProvider.GetUtcNow().UtcDateTime,});row.Salt = null;@@ -849,7 +848,7 @@ public class VaultController(/// <returns>The new revision number.</returns>private async Task<long> UpsertBucketAsync(AliasServerDbContext context, Guid manifestId, VaultDataBucketCategory kind, byte[] encryptedData, string? ciphertextHash, long? currentRevision, VaultDataBucket? existing){- var now = timeProvider.UtcNow;+ var now = timeProvider.GetUtcNow().UtcDateTime;if (existing is null){@@ -893,7 +892,7 @@ public class VaultController(var history = await context.VaultDataBucketsHistory.Where(x => x.ManifestId == manifestId && x.Category == kind && x.RevisionNumber != justArchived.RevisionNumber).ToListAsync();history.Add(justArchived);- var toDelete = VaultRetentionManager.ApplyRetention(_bucketRetentionPolicy, history, timeProvider.UtcNow);+ var toDelete = VaultRetentionManager.ApplyRetention(_bucketRetentionPolicy, history, timeProvider.GetUtcNow().UtcDateTime);if (toDelete.Count > 0){context.VaultDataBucketsHistory.RemoveRange(toDelete);@@ -912,7 +911,7 @@ public class VaultController(/// <returns>True when every payload is structurally valid; false when any is malformed (caller should 400).</returns>private async Task<bool> TryUpsertBlobObjectsAsync(AliasServerDbContext context, Guid manifestId, List<Blob> blobs, bool overwrite = false){- var nowUtc = timeProvider.UtcNow;+ var nowUtc = timeProvider.GetUtcNow().UtcDateTime;var hashes = blobs.Select(b => b.Hash).Distinct().ToList();var existing = await context.VaultBlobObjects.Where(b => b.ManifestId == manifestId && hashes.Contains(b.Hash))@@ -1022,7 +1021,7 @@ public class VaultController(historyRevisions.Add(justArchived);}- var revisionsToDelete = VaultRetentionManager.ApplyRetention(_manifestRetentionPolicy, historyRevisions, timeProvider.UtcNow, currentManifest);+ var revisionsToDelete = VaultRetentionManager.ApplyRetention(_manifestRetentionPolicy, historyRevisions, timeProvider.GetUtcNow().UtcDateTime, currentManifest);context.VaultManifestsHistory.RemoveRange(revisionsToDelete);// Blob references of pruned revisions are deleted explicitly (they only cascade with the whole manifest).@@ -1202,7 +1201,7 @@ public class VaultController(if (changed){- existing.UpdatedAt = timeProvider.UtcNow;+ existing.UpdatedAt = timeProvider.GetUtcNow().UtcDateTime;}continue;@@ -1235,8 +1234,8 @@ public class VaultController(Address = sanitized,AddressLocal = sanitized.Split('@')[0],AddressDomain = sanitized.Split('@')[1],- CreatedAt = timeProvider.UtcNow,- UpdatedAt = timeProvider.UtcNow,+ CreatedAt = timeProvider.GetUtcNow().UtcDateTime,+ UpdatedAt = timeProvider.GetUtcNow().UtcDateTime,});}@@ -1256,7 +1255,7 @@ public class VaultController(link.State = EmailClaimLinkState.Removed;}- claim.UpdatedAt = timeProvider.UtcNow;+ claim.UpdatedAt = timeProvider.GetUtcNow().UtcDateTime;}}@@ -1293,7 +1292,7 @@ public class VaultController(else{// Time-based cap: aliases created within the rolling window (create-then-delete still counts).- var windowStart = timeProvider.UtcNow.AddSeconds(-limit.WindowSeconds);+ var windowStart = timeProvider.GetUtcNow().UtcDateTime.AddSeconds(-limit.WindowSeconds);currentCount = await context.EmailClaimLinks.Where(l => l.EmailClaim.CreatedAt >= windowStart && l.VaultManifest.OwnerGroupId == groupId).Select(l => l.EmailClaimId).Distinct().CountAsync();}@@ -1331,14 +1330,14 @@ public class VaultController(foreach (var key in others){key.IsPrimary = false;- key.UpdatedAt = timeProvider.UtcNow;+ key.UpdatedAt = timeProvider.GetUtcNow().UtcDateTime;}var existingKey = others.FirstOrDefault(x => x.PublicKey == newPublicKey);if (existingKey != null){existingKey.IsPrimary = true;- existingKey.UpdatedAt = timeProvider.UtcNow;+ existingKey.UpdatedAt = timeProvider.GetUtcNow().UtcDateTime;return;}@@ -1348,8 +1347,8 @@ public class VaultController(Algorithm = VaultKeyAlgorithm.RsaOaepSha256,PublicKey = newPublicKey,IsPrimary = true,- CreatedAt = timeProvider.UtcNow,- UpdatedAt = timeProvider.UtcNow,+ CreatedAt = timeProvider.GetUtcNow().UtcDateTime,+ UpdatedAt = timeProvider.GetUtcNow().UtcDateTime,});}}diff --git a/apps/server/AliasVault.Api/Jwt/TimeValidationJwtBearerEvents.cs b/apps/server/AliasVault.Api/Jwt/TimeValidationJwtBearerEvents.csindex 22470ef7b..87096de6a 100644--- a/apps/server/AliasVault.Api/Jwt/TimeValidationJwtBearerEvents.cs+++ b/apps/server/AliasVault.Api/Jwt/TimeValidationJwtBearerEvents.cs@@ -7,19 +7,18 @@namespace AliasVault.Api.Jwt;-using AliasVault.Shared.Providers.Time;using Microsoft.AspNetCore.Authentication.JwtBearer;using Microsoft.IdentityModel.JsonWebTokens;/// <summary>/// JwtBearerEvents implementation that validates the token expiration time based on-/// the current time provided by an ITimeProvider. This is used to be able to+/// the current time provided by the injected TimeProvider. This is used to be able to/// test the token expiration logic in unit tests./// </summary>-public class TimeValidationJwtBearerEvents(ITimeProvider timeProvider) : JwtBearerEvents+public class TimeValidationJwtBearerEvents(TimeProvider timeProvider) : JwtBearerEvents{/// <summary>- /// Validates the token expiration time based on the current time provided by the ITimeProvider.+ /// Validates the token expiration time based on the current time provided by the TimeProvider./// </summary>/// <param name="context">TokenValidatedContext.</param>/// <returns>Async task.</returns>@@ -27,7 +26,7 @@ public class TimeValidationJwtBearerEvents(ITimeProvider timeProvider) : JwtBear{if (context.SecurityToken is JsonWebToken jwtToken){- var now = timeProvider.UtcNow;+ var now = timeProvider.GetUtcNow().UtcDateTime;if (jwtToken.ValidTo < now){context.Fail("Token has expired.");diff --git a/apps/server/AliasVault.Api/Program.cs b/apps/server/AliasVault.Api/Program.csindex 081da8aa1..3728122cd 100644--- a/apps/server/AliasVault.Api/Program.cs+++ b/apps/server/AliasVault.Api/Program.cs@@ -19,7 +19,6 @@ using AliasVault.Auth.IpAddress;using AliasVault.Cryptography;using AliasVault.Logging;using AliasVault.Shared.Models.Configuration;-using AliasVault.Shared.Providers.Time;using AliasVault.Shared.Server.Services;using AliasVault.Shared.Server.Utilities;using Asp.Versioning;@@ -80,7 +79,7 @@ builder.Services.ConfigureLogging(builder.Configuration, Assembly.GetExecutingAsbuilder.Services.AddAliasVaultDatabaseConfiguration(builder.Configuration);builder.Services.AddAliasVaultDataProtection("AliasVault.Api");-builder.Services.AddSingleton<ITimeProvider, SystemTimeProvider>();+builder.Services.AddSingleton(TimeProvider.System);builder.Services.AddScoped<TimeValidationJwtBearerEvents>();builder.Services.AddScoped<AuthLoggingService>();builder.Services.AddScoped<ServerSettingsService>();diff --git a/apps/server/AliasVault.Api/Services/CapabilityService.cs b/apps/server/AliasVault.Api/Services/CapabilityService.csindex 998d86560..b05ca329b 100644--- a/apps/server/AliasVault.Api/Services/CapabilityService.cs+++ b/apps/server/AliasVault.Api/Services/CapabilityService.cs@@ -9,7 +9,6 @@ namespace AliasVault.Api.Services;using AliasServerDb;using AliasVault.Api.Headers;-using AliasVault.Shared.Providers.Time;using AliasVault.Shared.Server.Capabilities;using Microsoft.EntityFrameworkCore;using Microsoft.Extensions.Caching.Memory;@@ -19,8 +18,8 @@ using Microsoft.Extensions.Caching.Memory;/// </summary>/// <param name="dbContextFactory">IDbContextFactory instance.</param>/// <param name="cache">IMemoryCache instance used to cache the enabled rules.</param>-/// <param name="timeProvider">ITimeProvider instance.</param>-public class CapabilityService(IAliasServerDbContextFactory dbContextFactory, IMemoryCache cache, ITimeProvider timeProvider)+/// <param name="timeProvider">TimeProvider instance.</param>+public class CapabilityService(IAliasServerDbContextFactory dbContextFactory, IMemoryCache cache, TimeProvider timeProvider){private const int CacheDurationSeconds = 60;@@ -36,7 +35,7 @@ public class CapabilityService(IAliasServerDbContextFactory dbContextFactory, IM{var rules = await GetEnabledRulesAsync();var subject = await BuildSubjectAsync(userId, clientHeader, rules);- var resolved = CapabilityResolver.ResolveAll(rules, subject, timeProvider.UtcNow);+ var resolved = CapabilityResolver.ResolveAll(rules, subject, timeProvider.GetUtcNow().UtcDateTime);/** Filter on the off value itself rather than on IsEnabled: values are strings so one can carry a cap or a@@ -57,7 +56,7 @@ public class CapabilityService(IAliasServerDbContextFactory dbContextFactory, IM{var rules = await GetEnabledRulesAsync();var subject = await BuildSubjectAsync(userId, clientHeader, rules);- return CapabilityValue.IsEnabled(CapabilityResolver.Resolve(rules, subject, capabilityKey, timeProvider.UtcNow));+ return CapabilityValue.IsEnabled(CapabilityResolver.Resolve(rules, subject, capabilityKey, timeProvider.GetUtcNow().UtcDateTime));}/// <summary>diff --git a/apps/server/AliasVault.Api/Services/RateLimitService.cs b/apps/server/AliasVault.Api/Services/RateLimitService.csindex d7b5d0a9a..a0a3bf438 100644--- a/apps/server/AliasVault.Api/Services/RateLimitService.cs+++ b/apps/server/AliasVault.Api/Services/RateLimitService.cs@@ -8,7 +8,6 @@namespace AliasVault.Api.Services;using AliasServerDb;-using AliasVault.Shared.Providers.Time;using Microsoft.EntityFrameworkCore;using Microsoft.Extensions.Caching.Memory;@@ -19,8 +18,8 @@ using Microsoft.Extensions.Caching.Memory;/// </summary>/// <param name="dbContextFactory">IDbContextFactory instance.</param>/// <param name="cache">IMemoryCache instance used to cache the enabled rules.</param>-/// <param name="timeProvider">ITimeProvider instance.</param>-public class RateLimitService(IAliasServerDbContextFactory dbContextFactory, IMemoryCache cache, ITimeProvider timeProvider)+/// <param name="timeProvider">TimeProvider instance.</param>+public class RateLimitService(IAliasServerDbContextFactory dbContextFactory, IMemoryCache cache, TimeProvider timeProvider){private const int CacheDurationSeconds = 60;@@ -35,7 +34,7 @@ public class RateLimitService(IAliasServerDbContextFactory dbContextFactory, IMepublic async Task<IReadOnlyList<EffectiveRateLimit>> GetLimitsAsync(Group group, RateLimitType limitType){var rules = await GetEnabledRulesAsync();- return RateLimitResolver.Resolve(rules, group, limitType, timeProvider.UtcNow);+ return RateLimitResolver.Resolve(rules, group, limitType, timeProvider.GetUtcNow().UtcDateTime);}/// <summary>diff --git a/apps/server/Databases/AliasClientDb/AliasClientDb.csproj b/apps/server/Databases/AliasClientDb/AliasClientDb.csprojindex 02f757ae2..ecfbfbc00 100644--- a/apps/server/Databases/AliasClientDb/AliasClientDb.csproj+++ b/apps/server/Databases/AliasClientDb/AliasClientDb.csproj@@ -25,7 +25,6 @@<PrivateAssets>all</PrivateAssets><IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets></PackageReference>- <PackageReference Include="Microsoft.EntityFrameworkCore.Proxies" Version="10.0.10" /><PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="10.0.10" /><PackageReference Include="Microsoft.Extensions.Configuration" Version="10.0.10" /><PackageReference Include="Microsoft.Extensions.Configuration.FileExtensions" Version="10.0.10" />diff --git a/apps/server/Databases/AliasClientDb/AliasClientDbContext.cs b/apps/server/Databases/AliasClientDb/AliasClientDbContext.csindex 1e76971ad..c135e62f6 100644--- a/apps/server/Databases/AliasClientDb/AliasClientDbContext.cs+++ b/apps/server/Databases/AliasClientDb/AliasClientDbContext.cs@@ -8,7 +8,6 @@namespace AliasClientDb;using System.Globalization;-using Microsoft.Data.Sqlite;using Microsoft.EntityFrameworkCore;using Microsoft.EntityFrameworkCore.Storage.ValueConversion;using Microsoft.Extensions.Configuration;@@ -25,16 +24,6 @@ public class AliasClientDbContext : DbContext{}- /// <summary>- /// Initializes a new instance of the <see cref="AliasClientDbContext"/> class.- /// </summary>- /// <param name="sqliteConnection">The SQLite connection to use to connect to the SQLite database.</param>- /// <param name="logAction">The action to perform for logging.</param>- public AliasClientDbContext(SqliteConnection sqliteConnection, Action<string> logAction)- : base(GetOptions(sqliteConnection, logAction))- {- }-/// <summary>/// Initializes a new instance of the <see cref="AliasClientDbContext"/> class./// </summary>@@ -350,9 +339,7 @@ public class AliasClientDbContext : DbContext.AddJsonFile("appsettings.json").Build();- optionsBuilder- .UseSqlite(configuration.GetConnectionString("AliasClientDbContext"))- .UseLazyLoadingProxies();+ optionsBuilder.UseSqlite(configuration.GetConnectionString("AliasClientDbContext"));// Log queries made as debug output.optionsBuilder.LogTo(Console.WriteLine);@@ -361,21 +348,6 @@ public class AliasClientDbContext : DbContextbase.OnConfiguring(optionsBuilder);}- /// <summary>- /// Gets the options for the AliasClientDbContext.- /// </summary>- /// <param name="connection">The SQLite connection to use to connect to the SQLite database.</param>- /// <param name="logAction">The action to perform for logging.</param>- /// <returns>The options for the AliasClientDbContext.</returns>- private static DbContextOptions<AliasClientDbContext> GetOptions(SqliteConnection connection, Action<string> logAction)- {- var optionsBuilder = new DbContextOptionsBuilder<AliasClientDbContext>();- optionsBuilder.UseSqlite(connection);- optionsBuilder.LogTo(logAction, new[] { DbLoggerCategory.Database.Command.Name });-- return optionsBuilder.Options;- }-/// <summary>/// Converts a DateTime to a string in the standard format: "yyyy-MM-dd HH:mm:ss.fff" (23 characters with milliseconds)./// This format ensures SQLite native support, consistent precision, and proper sorting.diff --git a/apps/server/Databases/AliasClientDb/Scripts/README.md b/apps/server/Databases/AliasClientDb/Scripts/README.mdindex 0a0ba7a76..ad21a389f 100644--- a/apps/server/Databases/AliasClientDb/Scripts/README.md+++ b/apps/server/Databases/AliasClientDb/Scripts/README.md@@ -4,7 +4,7 @@ This directory contains scripts to generate SQL files from Entity Framework CoreThis library is consumed by the web app, browser extensions and mobile apps for vault creation and upgrades.-Refer to the docs `upgrade-ef-client-model.md` for how this scripts are used.+Run `./run-all.sh` after adding an EF migration to regenerate the SQL files and `core/vault/src/sql/SqlConstants.ts`.## The migration chain is frozen at vault version 2.0.0diff --git a/apps/server/README.md b/apps/server/README.mdindex ec714d7c0..d3cde406e 100644--- a/apps/server/README.md+++ b/apps/server/README.md@@ -1 +1 @@-This folder contains the .NET source code and project solution files for AliasVault which includes the main client and API.+This folder contains the .NET source code and project solution files for AliasVault which includes the API, Admin portal and background services (SMTP, task runner).diff --git a/apps/server/Shared/AliasVault.Shared/Providers/Time/ITimeProvider.cs b/apps/server/Shared/AliasVault.Shared/Providers/Time/ITimeProvider.csdeleted file mode 100644index 8d944d358..000000000--- a/apps/server/Shared/AliasVault.Shared/Providers/Time/ITimeProvider.cs+++ /dev/null@@ -1,19 +0,0 @@-// ------------------------------------------------------------------------// <copyright file="ITimeProvider.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>-/// Time provider interface for getting the current time. We use this to be able to mock the time in tests.-/// </summary>-public interface ITimeProvider-{- /// <summary>- /// Gets current time in UTC.- /// </summary>- DateTime UtcNow { get; }-}diff --git a/apps/server/Shared/AliasVault.Shared/Providers/Time/SystemTimeProvider.cs b/apps/server/Shared/AliasVault.Shared/Providers/Time/SystemTimeProvider.csdeleted file mode 100644index ce7e78d1d..000000000--- a/apps/server/Shared/AliasVault.Shared/Providers/Time/SystemTimeProvider.cs+++ /dev/null@@ -1,19 +0,0 @@-// ------------------------------------------------------------------------// <copyright file="SystemTimeProvider.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>-/// Default time provider that uses the system clock.-/// </summary>-public class SystemTimeProvider : ITimeProvider-{- /// <summary>- /// Gets current time in UTC.- /// </summary>- public DateTime UtcNow => DateTime.UtcNow;-}diff --git a/apps/server/Tests/AliasVault.E2ETests/Common/AdminPlaywrightTest.cs b/apps/server/Tests/AliasVault.E2ETests/Common/AdminPlaywrightTest.csindex 3fe346b2c..fc204cd66 100644--- a/apps/server/Tests/AliasVault.E2ETests/Common/AdminPlaywrightTest.cs+++ b/apps/server/Tests/AliasVault.E2ETests/Common/AdminPlaywrightTest.cs@@ -5,14 +5,21 @@// </copyright>//-----------------------------------------------------------------------+// Run tests in parallel with a maximum of 1 parallel tests (= not parallel).+// Increasing the level of parallelism can lead to concurrency issues especially+// when running tests through GitHub Actions where the retry will take+// longer to complete as opposed to running just one test at a time.+[assembly: LevelOfParallelism(1)]+namespace AliasVault.E2ETests.Common;using AliasServerDb;+using Microsoft.Extensions.Configuration;/// <summary>/// Base class for Playwright E2E tests that run against Admin webapp./// </summary>-public abstract class AdminPlaywrightTest : PlaywrightTest+public abstract class AdminPlaywrightTest{private const int BasePort = 5700;private static int _currentPort = BasePort;@@ -20,13 +27,91 @@ public abstract class AdminPlaywrightTest : PlaywrightTest/// <summary>/// For starting the Admin project in-memory./// </summary>- private readonly WebApplicationAdminFactoryFixture<AliasVault.Admin.Program> _webAppFactory = new();+ private readonly WebApplicationAdminFactoryFixture _webAppFactory = new();++ /// <summary>+ /// Gets or sets the admin username used to log in.+ /// </summary>+ protected string TestUserUsername { get; set; } = "admin";++ /// <summary>+ /// Gets or sets the admin password used to log in, based on the ADMIN_PASSWORD_HASH set by WebApplicationAdminFactoryFixture.+ /// </summary>+ protected string TestUserPassword { get; set; } = "password";++ /// <summary>+ /// Gets or sets the Playwright browser instance.+ /// </summary>+ protected IBrowser? Browser { get; set; }++ /// <summary>+ /// Gets or sets the Playwright browser context.+ /// </summary>+ protected IBrowserContext Context { get; set; } = null!;++ /// <summary>+ /// Gets or sets the Playwright page.+ /// </summary>+ protected IPage Page { get; set; } = null!;++ /// <summary>+ /// Gets or sets the input helper for Playwright tests.+ /// </summary>+ protected PlaywrightInputHelper InputHelper { get; set; } = null!;++ /// <summary>+ /// Gets or sets base URL where the app under test runs on including random port.+ /// </summary>+ protected string AppBaseUrl { get; set; } = string.Empty;/// <summary>/// Gets the db context for the Admin project./// </summary>protected AliasServerDbContext DbContext => _webAppFactory.GetDbContext();+ /// <summary>+ /// One time setup for the Playwright test which runs before all tests in the class.+ /// </summary>+ /// <returns>Async task.</returns>+ [OneTimeSetUp]+ public async Task OneTimeSetUp()+ {+ const int maxRetries = 10;+ int currentRetry = 0;++ while (currentRetry < maxRetries)+ {+ try+ {+ await SetupEnvironment();+ return;+ }+ catch (PlaywrightException)+ {+ throw;+ }+ catch (AggregateException)+ {+ throw;+ }+ catch (ArgumentException)+ {+ throw;+ }+ catch (Exception ex)+ {+ currentRetry++;+ Console.WriteLine($"Attempt {currentRetry} failed: {ex.Message}");+ if (currentRetry >= maxRetries)+ {+ Console.WriteLine($"All {maxRetries} attempts failed. Last exception: {ex}");+ }++ await Task.Delay(500);+ }+ }+ }+/// <summary>/// Tear down the Playwright test which runs after all tests are done in the class./// </summary>@@ -45,39 +130,71 @@ public abstract class AdminPlaywrightTest : PlaywrightTest}/// <summary>- /// Setup the Playwright test environment.+ /// Navigate to a relative URL using Blazor's client-side router./// </summary>- /// <returns>Async task.</returns>- protected override async Task SetupEnvironment()+ /// <param name="relativeUrl">Relative URL.</param>+ /// <returns>Task.</returns>+ protected async Task NavigateUsingBlazorRouter(string relativeUrl){- // Set the base port for the test starting at 5600. Increase the port by 2 for each test running- // in parallel to avoid port conflicts.- int appPort;- lock (Lock)+ const int maxRetries = 3;++ for (int attempt = 1; attempt <= maxRetries; attempt++){- appPort = Interlocked.Increment(ref _currentPort);+ try+ {+ await NavigateUsingBlazorRouterInternal(relativeUrl);+ return;+ }+ catch (TimeoutException) when (attempt < maxRetries)+ {+ Console.WriteLine($"Navigation to '{relativeUrl}' failed (attempt {attempt}/{maxRetries}), retrying...");+ await Task.Delay(500);+ }}+ }- AppBaseUrl = "http://localhost:" + appPort + "/";+ /// <summary>+ /// Navigate to a relative URL using the browser's navigation.+ /// </summary>+ /// <param name="relativeUrl">Relative URL.</param>+ /// <returns>Task.</returns>+ protected async Task NavigateBrowser(string relativeUrl)+ {+ await Page.GotoAsync(AppBaseUrl + relativeUrl);- // Start Admin project in-memory.- _webAppFactory.Port = appPort;- _webAppFactory.InitializeKestrel();- _webAppFactory.CreateDefaultClient();+ // Wait for Blazor to load completely+ await Page.WaitForLoadStateAsync(LoadState.NetworkIdle);+ }- await SetupPlaywrightBrowserAndContext();- Page = await Context.NewPageAsync();- InputHelper = new(Page);+ /// <summary>+ /// Wait for the specified URL to be loaded with a default timeout.+ /// </summary>+ /// <param name="relativeUrl">The relative URL to wait for e.g. "home". This may also contain wildcard such as "user/login**".</param>+ /// <returns>Async task.</returns>+ protected async Task WaitForUrlAsync(string relativeUrl)+ {+ await Page.WaitForURLAsync("**/" + relativeUrl, new PageWaitForURLOptions() { Timeout = TestDefaults.DefaultTimeout });+ }- // Check that we get redirected to /user/login when accessing the root URL and not authenticated.- await Page.GotoAsync(AppBaseUrl);- await WaitForUrlAsync("user/login**");+ /// <summary>+ /// Wait for the specified URL to be loaded and a certain text to appear on the page.+ /// </summary>+ /// <param name="relativeUrl">The relative URL to wait for e.g. "home". This may also contain wildcard such as "user/login**".</param>+ /// <param name="waitForText">Wait until a certain text appears on the page.+ /// This can be useful for content that is loaded via AJAX after navigation.</param>+ /// <returns>Async task.</returns>+ protected async Task WaitForUrlAsync(string relativeUrl, string waitForText)+ {+ await Page.WaitForURLAsync("**/" + relativeUrl, new PageWaitForURLOptions() { Timeout = TestDefaults.DefaultTimeout });- // These credentials are based on the static environment variables set by WebApplicationAdminFactoryFixture.cs- // for this test.- TestUserUsername = "admin";- TestUserPassword = "password";- await LoginAsAdmin();+ // Wait for actual content to load (web API calls, etc.)+ await Page.GetByText(waitForText, new PageGetByTextOptions { Exact = false })+ .First+ .WaitForAsync(new LocatorWaitForOptions+ {+ Timeout = TestDefaults.DefaultTimeout,+ State = WaitForSelectorState.Attached,+ });}/// <summary>@@ -115,4 +232,112 @@ public abstract class AdminPlaywrightTest : PlaywrightTestvar pageContent = await Page.TextContentAsync("body");Assert.That(pageContent, Does.Contain("Welcome to the AliasVault admin dashboard"), "No entry page content visible after logging in to admin app.");}++ /// <summary>+ /// Start the Admin project in-memory, open a browser and log in as admin.+ /// </summary>+ /// <returns>Async task.</returns>+ private async Task SetupEnvironment()+ {+ // Each test class gets its own port to avoid conflicts.+ var appPort = Interlocked.Increment(ref _currentPort);+ AppBaseUrl = "http://localhost:" + appPort + "/";++ // Start Admin project in-memory.+ _webAppFactory.Port = appPort;+ _webAppFactory.InitializeKestrel();+ _webAppFactory.CreateDefaultClient();++ await SetupPlaywrightBrowserAndContext();+ Page = await Context.NewPageAsync();+ InputHelper = new(Page);++ // Check that we get redirected to /user/login when accessing the root URL and not authenticated.+ await Page.GotoAsync(AppBaseUrl);+ await WaitForUrlAsync("user/login**");++ await LoginAsAdmin();+ }++ /// <summary>+ /// Setup the Playwright browser and context based on settings defined in appsettings.json.+ /// </summary>+ /// <returns>Task.</returns>+ private async Task SetupPlaywrightBrowserAndContext()+ {+ // Set Playwright headless mode based on appsettings.json value.+ var configuration = new ConfigurationBuilder()+ .SetBasePath(Directory.GetCurrentDirectory())+ .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)+ .AddJsonFile($"appsettings.Development.json", optional: true, reloadOnChange: true)+ .AddEnvironmentVariables()+ .Build();++ bool headless = configuration.GetValue("PlaywrightSettings:Headless", true);++ var playwright = await Playwright.CreateAsync();+ Browser = await playwright.Chromium.LaunchAsync(new BrowserTypeLaunchOptions { Headless = headless });+ Context = await Browser.NewContextAsync();++ // Set up console message logging to help debug CI issues+ Context.Console += (_, msg) =>+ {+ var type = msg.Type;+ var text = msg.Text;++ var logMessage = $"[CONTEXT CONSOLE {type.ToUpper()}] {text}";++ // Write to multiple outputs to ensure visibility+ if (type == "error")+ {+ TestContext.Progress.WriteLine(logMessage);+ Console.Error.WriteLine(logMessage);+ }+ };++ // Log failed requests to help identify network issues+ Context.RequestFailed += (_, request) =>+ {+ var failureMessage = $"[REQUEST FAILED] {request.Failure} - {request.Url}";+ Console.WriteLine(failureMessage);+ Console.Error.WriteLine(failureMessage);+ TestContext.Progress.WriteLine(failureMessage);+ };+ }++ /// <summary>+ /// Internal navigation implementation.+ /// </summary>+ /// <param name="relativeUrl">Relative URL.</param>+ /// <returns>Task.</returns>+ private async Task NavigateUsingBlazorRouterInternal(string relativeUrl)+ {+ // Navigate to the app's base URL initially if not already there+ if (!Page.Url.StartsWith(AppBaseUrl))+ {+ await Page.GotoAsync(AppBaseUrl);++ // Wait for Blazor to load completely+ await Page.WaitForLoadStateAsync(LoadState.NetworkIdle);+ }++ // Check if we're already on the target URL (pattern matching)+ var targetPattern = new System.Text.RegularExpressions.Regex(@".*/" + System.Text.RegularExpressions.Regex.Escape(relativeUrl) + @"(\?.*)?$");+ var alreadyOnTarget = targetPattern.IsMatch(Page.Url);++ // Perform soft navigation within the app+ await Page.EvaluateAsync($"window.blazorNavigate('{relativeUrl}')");++ // Only wait for URL change if we weren't already on the target URL+ if (!alreadyOnTarget)+ {+ await Page.WaitForURLAsync("**/" + relativeUrl, new PageWaitForURLOptions+ {+ Timeout = TestDefaults.DefaultTimeout,+ });+ }++ // Always wait for the network to settle after navigation+ await Page.WaitForLoadStateAsync(LoadState.NetworkIdle);+ }}diff --git a/apps/server/Tests/AliasVault.E2ETests/Common/PlaywrightTest.cs b/apps/server/Tests/AliasVault.E2ETests/Common/PlaywrightTest.csdeleted file mode 100644index 884662006..000000000--- a/apps/server/Tests/AliasVault.E2ETests/Common/PlaywrightTest.cs+++ /dev/null@@ -1,273 +0,0 @@-//------------------------------------------------------------------------// <copyright file="PlaywrightTest.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>-//-------------------------------------------------------------------------// Run tests in parallel with a maximum of 1 parallel tests (= not parallel).-// Increasing the level of parallelism can lead to concurrency issues especially-// when running tests through GitHub Actions where the retry will take-// longer to complete as opposed to running just one test at a time.-[assembly: LevelOfParallelism(1)]--namespace AliasVault.E2ETests.Common;--using Microsoft.Extensions.Configuration;-using Microsoft.Playwright;--/// <summary>-/// Base class for tests that use Playwright for E2E browser testing.-/// </summary>-public abstract class PlaywrightTest-{- /// <summary>- /// Lock object for thread safety.- /// </summary>- protected static readonly object Lock = new();-- /// <summary>- /// Gets or sets random unique account email that is used for the test.- /// </summary>- protected virtual string TestUserUsername { get; set; } = $"{Guid.NewGuid().ToString()[..10]}@test.com";-- /// <summary>- /// Gets or sets random unique account password that is used for the test.- /// </summary>- protected virtual string TestUserPassword { get; set; } = Guid.NewGuid().ToString();-- /// <summary>- /// Gets or sets the Playwright browser instance.- /// </summary>- protected IBrowser? Browser { get; set; }-- /// <summary>- /// Gets or sets the Playwright browser context.- /// </summary>- protected IBrowserContext Context { get; set; } = null!;-- /// <summary>- /// Gets or sets the Playwright page.- /// </summary>- protected IPage Page { get; set; } = null!;-- /// <summary>- /// Gets or sets the input helper for Playwright tests.- /// </summary>- protected PlaywrightInputHelper InputHelper { get; set; } = null!;-- /// <summary>- /// Gets or sets base URL where the app under test runs on including random port.- /// </summary>- protected string AppBaseUrl { get; set; } = string.Empty;-- /// <summary>- /// One time setup for the Playwright test which runs before all tests in the class.- /// </summary>- /// <returns>Async task.</returns>- [OneTimeSetUp]- public virtual async Task OneTimeSetUp()- {- const int maxRetries = 10;- int currentRetry = 0;-- while (currentRetry < maxRetries)- {- try- {- await SetupEnvironment();- return;- }- catch (PlaywrightException)- {- throw;- }- catch (AggregateException)- {- throw;- }- catch (ArgumentException)- {- throw;- }- catch (Exception ex)- {- currentRetry++;- Console.WriteLine($"Attempt {currentRetry} failed: {ex.Message}");- if (currentRetry >= maxRetries)- {- Console.WriteLine($"All {maxRetries} attempts failed. Last exception: {ex}");- }-- await Task.Delay(500);- }- }- }-- /// <summary>- /// Navigate to a relative URL using Blazor's client-side router.- /// </summary>- /// <param name="relativeUrl">Relative URL.</param>- /// <returns>Task.</returns>- protected async Task NavigateUsingBlazorRouter(string relativeUrl)- {- const int maxRetries = 3;-- for (int attempt = 1; attempt <= maxRetries; attempt++)- {- try- {- await NavigateUsingBlazorRouterInternal(relativeUrl);- return;- }- catch (TimeoutException) when (attempt < maxRetries)- {- Console.WriteLine($"Navigation to '{relativeUrl}' failed (attempt {attempt}/{maxRetries}), retrying...");- await Task.Delay(500);- }- }- }-- /// <summary>- /// Navigate to a relative URL using the browser's navigation.- /// </summary>- /// <param name="relativeUrl">Relative URL.</param>- /// <returns>Task.</returns>- protected async Task NavigateBrowser(string relativeUrl)- {- await Page.GotoAsync(AppBaseUrl + relativeUrl);-- // Wait for Blazor to load completely- await Page.WaitForLoadStateAsync(LoadState.NetworkIdle);- }-- /// <summary>- /// Wait for the specified URL to be loaded with a default timeout.- /// </summary>- /// <param name="relativeUrl">The relative URL to wait for e.g. "home". This may also contain wildcard such as "user/login**".</param>- /// <returns>Async task.</returns>- protected async Task WaitForUrlAsync(string relativeUrl)- {- await Page.WaitForURLAsync("**/" + relativeUrl, new PageWaitForURLOptions() { Timeout = TestDefaults.DefaultTimeout });- }-- /// <summary>- /// Wait for the specified URL to be loaded with a custom timeout.- /// </summary>- /// <param name="relativeUrl">The relative URL to wait for e.g. "home". This may also contain wildcard such as "user/login**".</param>- /// <param name="timeoutInMs">Custom timeout in milliseconds.</param>- /// <returns>Async task.</returns>- protected async Task WaitForUrlAsync(string relativeUrl, int timeoutInMs)- {- await Page.WaitForURLAsync("**/" + relativeUrl, new PageWaitForURLOptions() { Timeout = timeoutInMs });- }-- /// <summary>- /// Wait for the specified URL to be loaded with a custom timeout.- /// </summary>- /// <param name="relativeUrl">The relative URL to wait for e.g. "home". This may also contain wildcard such as "user/login**".</param>- /// <param name="waitForText">Wait until a certain text appears on the page.- /// This can be useful for content that is loaded via AJAX after navigation.</param>- /// <returns>Async task.</returns>- protected async Task WaitForUrlAsync(string relativeUrl, string waitForText)- {- await Page.WaitForURLAsync("**/" + relativeUrl, new PageWaitForURLOptions() { Timeout = TestDefaults.DefaultTimeout });-- // Wait for actual content to load (web API calls, etc.)- await Page.GetByText(waitForText, new PageGetByTextOptions { Exact = false })- .First- .WaitForAsync(new LocatorWaitForOptions- {- Timeout = TestDefaults.DefaultTimeout,- State = WaitForSelectorState.Attached,- });- }-- /// <summary>- /// Setup the Playwright browser and context based on settings defined in appsettings.json.- /// </summary>- /// <returns>Task.</returns>- protected virtual async Task SetupPlaywrightBrowserAndContext()- {- // Set Playwright headless mode based on appsettings.json value.- var configuration = new ConfigurationBuilder()- .SetBasePath(Directory.GetCurrentDirectory())- .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)- .AddJsonFile($"appsettings.Development.json", optional: true, reloadOnChange: true)- .AddEnvironmentVariables()- .Build();-- bool headless = configuration.GetValue("PlaywrightSettings:Headless", true);-- var playwright = await Playwright.CreateAsync();- Browser = await playwright.Chromium.LaunchAsync(new BrowserTypeLaunchOptions { Headless = headless });- Context = await Browser.NewContextAsync();-- // Set up console message logging to help debug CI issues- Context.Console += (_, msg) =>- {- var type = msg.Type;- var text = msg.Text;-- var logMessage = $"[CONTEXT CONSOLE {type.ToUpper()}] {text}";-- // Write to multiple outputs to ensure visibility- if (type == "error")- {- TestContext.Progress.WriteLine(logMessage);- Console.Error.WriteLine(logMessage);- }- };-- // Log failed requests to help identify network issues- Context.RequestFailed += (_, request) =>- {- var failureMessage = $"[REQUEST FAILED] {request.Failure} - {request.Url}";- Console.WriteLine(failureMessage);- Console.Error.WriteLine(failureMessage);- TestContext.Progress.WriteLine(failureMessage);- };- }-- /// <summary>- /// Set up the Playwright test environment. This method is required to be implemented by the derived class.- /// </summary>- /// <returns>Async task.</returns>- protected abstract Task SetupEnvironment();-- /// <summary>- /// Internal navigation implementation.- /// </summary>- /// <param name="relativeUrl">Relative URL.</param>- /// <returns>Task.</returns>- private async Task NavigateUsingBlazorRouterInternal(string relativeUrl)- {- // Navigate to the app's base URL initially if not already there- if (!Page.Url.StartsWith(AppBaseUrl))- {- await Page.GotoAsync(AppBaseUrl);-- // Wait for Blazor to load completely- await Page.WaitForLoadStateAsync(LoadState.NetworkIdle);- }-- // Check if we're already on the target URL (pattern matching)- var targetPattern = new System.Text.RegularExpressions.Regex(@".*/" + System.Text.RegularExpressions.Regex.Escape(relativeUrl) + @"(\?.*)?$");- var alreadyOnTarget = targetPattern.IsMatch(Page.Url);-- // Perform soft navigation within the app- await Page.EvaluateAsync($"window.blazorNavigate('{relativeUrl}')");-- // Only wait for URL change if we weren't already on the target URL- if (!alreadyOnTarget)- {- await Page.WaitForURLAsync("**/" + relativeUrl, new PageWaitForURLOptions- {- Timeout = TestDefaults.DefaultTimeout,- });- }-- // Always wait for the network to settle after navigation- await Page.WaitForLoadStateAsync(LoadState.NetworkIdle);- }-}diff --git a/apps/server/Tests/AliasVault.E2ETests/Infrastructure/Abstracts/WebApplicationFactoryFixture.cs b/apps/server/Tests/AliasVault.E2ETests/Infrastructure/Abstracts/WebApplicationFactoryFixture.csdeleted file mode 100644index 51b903534..000000000--- a/apps/server/Tests/AliasVault.E2ETests/Infrastructure/Abstracts/WebApplicationFactoryFixture.cs+++ /dev/null@@ -1,188 +0,0 @@-//------------------------------------------------------------------------// <copyright file="WebApplicationFactoryFixture.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.Abstracts;--using AliasServerDb;-using AliasVault.Shared.Server.Services;-using Microsoft.AspNetCore.Hosting;-using Microsoft.AspNetCore.Mvc.Testing;-using Microsoft.Extensions.DependencyInjection;-using Microsoft.Extensions.Hosting;-using Npgsql;--/// <summary>-/// Base class for web application factory fixture for integration tests.-/// </summary>-/// <typeparam name="TEntryPoint">The entry point.</typeparam>-public abstract class WebApplicationFactoryFixture<TEntryPoint> : WebApplicationFactory<TEntryPoint>- where TEntryPoint : class-{- /// <summary>- /// The DbContextFactory instance that is created for the test.- /// </summary>- private IAliasServerDbContextFactory _dbContextFactory = null!;-- /// <summary>- /// The cached DbContext instance that can be used during the test.- /// </summary>- private AliasServerDbContext? _dbContext;-- /// <summary>- /// The ServerSettingsService instance that is created for the test.- /// </summary>- private IServiceScope? _scope;-- /// <summary>- /// The name of the temporary test database.- /// </summary>- private string? _tempDbName;-- /// <summary>- /// Whether UseKestrel has been called.- /// </summary>- private bool _kestrelConfigured;-- /// <summary>- /// Gets or sets the port the web application kestrel host will listen on.- /// </summary>- public abstract int Port { get; set; }-- /// <summary>- /// Returns the DbContext instance for the test. This can be used to seed the database with test data.- /// </summary>- /// <returns>AliasServerDbContext instance.</returns>- public AliasServerDbContext GetDbContext()- {- if (_dbContext != null)- {- return _dbContext;- }-- _dbContext = _dbContextFactory.CreateDbContext();- return _dbContext;- }-- /// <summary>- /// Gets the ServerSettingsService instance for mutating server settings in tests.- /// </summary>- /// <returns>ServerSettingsService instance.</returns>- public ServerSettingsService GetServerSettings()- {- _scope?.Dispose();- _scope = Services.CreateScope();- return _scope.ServiceProvider.GetRequiredService<ServerSettingsService>();- }-- /// <summary>- /// Disposes the DbConnection instance and drops the temporary database.- /// </summary>- /// <returns>Task.</returns>- public override async ValueTask DisposeAsync()- {- if (_dbContext != null)- {- await _dbContext.DisposeAsync();- _dbContext = null;- }-- _scope?.Dispose();-- if (!string.IsNullOrEmpty(_tempDbName))- {- // Create a connection to 'postgres' database to drop the test database- using var conn = new NpgsqlConnection("Host=localhost;Port=5109;Database=postgres;Username=aliasvault;Password=password");- await conn.OpenAsync();-- // First terminate existing connections- using (var cmd = conn.CreateCommand())- {- cmd.CommandText = $"""- SELECT pg_terminate_backend(pid)- FROM pg_stat_activity- WHERE datname = '{_tempDbName}';- """;- await cmd.ExecuteNonQueryAsync();- }-- // Then drop the database in a separate command- using (var cmd = conn.CreateCommand())- {- cmd.CommandText = $"""- DROP DATABASE IF EXISTS "{_tempDbName}";- """;- await cmd.ExecuteNonQueryAsync();- }- }-- GC.SuppressFinalize(this);- await base.DisposeAsync();- }-- /// <summary>- /// Initializes the factory with Kestrel on the specified port.- /// Must be called before CreateDefaultClient() in tests.- /// </summary>- public void InitializeKestrel()- {- if (!_kestrelConfigured)- {- UseKestrel(Port);- _kestrelConfigured = true;- }- }-- /// <inheritdoc />- protected override IHost CreateHost(IHostBuilder builder)- {- var host = base.CreateHost(builder);-- // Get the DbContextFactory instance and store it for later use during tests.- _dbContextFactory = host.Services.GetRequiredService<IAliasServerDbContextFactory>();-- return host;- }-- /// <inheritdoc />- protected override void ConfigureWebHost(IWebHostBuilder builder)- {- _tempDbName = $"aliasdb_test_{Guid.NewGuid()}";- SetEnvironmentVariables();-- builder.ConfigureServices(services =>- {- RemoveExistingRegistrations(services);- AddNewRegistrations(services);- });- }-- /// <summary>- /// Adds new service registrations.- /// </summary>- /// <param name="services">The <see cref="IServiceCollection"/> to modify.</param>- protected abstract void AddNewRegistrations(IServiceCollection services);-- /// <summary>- /// Removes existing service registrations.- /// </summary>- /// <param name="services">The <see cref="IServiceCollection"/> to modify.</param>- protected abstract void RemoveExistingRegistrations(IServiceCollection services);-- /// <summary>- /// Sets the required environment variables for testing.- /// </summary>- private void SetEnvironmentVariables()- {- Environment.SetEnvironmentVariable("ConnectionStrings__AliasServerDbContext", "Host=localhost;Port=5109;Database=" + _tempDbName + ";Username=aliasvault;Password=password");- Environment.SetEnvironmentVariable("JWT_KEY", "12345678901234567890123456789012");- Environment.SetEnvironmentVariable("DATA_PROTECTION_CERT_PASS", "Development");- Environment.SetEnvironmentVariable("PUBLIC_REGISTRATION_ENABLED", "true");- Environment.SetEnvironmentVariable("ADMIN_PASSWORD_HASH", "AQAAAAIAAYagAAAAEKWfKfa2gh9Z72vjAlnNP1xlME7FsunRznzyrfqFte40FToufRwa3kX8wwDwnEXZag==");- Environment.SetEnvironmentVariable("ADMIN_PASSWORD_GENERATED", "2024-01-01T00:00:00Z");- Environment.SetEnvironmentVariable("ALIASVAULT_TEST_MODE", "true");- }-}diff --git a/apps/server/Tests/AliasVault.E2ETests/Infrastructure/WebApplicationAdminFactoryFixture.cs b/apps/server/Tests/AliasVault.E2ETests/Infrastructure/WebApplicationAdminFactoryFixture.csindex f6568b610..178980842 100644--- a/apps/server/Tests/AliasVault.E2ETests/Infrastructure/WebApplicationAdminFactoryFixture.cs+++ b/apps/server/Tests/AliasVault.E2ETests/Infrastructure/WebApplicationAdminFactoryFixture.cs@@ -7,48 +7,151 @@namespace AliasVault.E2ETests.Infrastructure;+using AliasServerDb;using AliasVault.Admin.Services;-using AliasVault.E2ETests.Infrastructure.Abstracts;+using Microsoft.AspNetCore.Hosting;+using Microsoft.AspNetCore.Mvc.Testing;using Microsoft.Extensions.DependencyInjection;+using Microsoft.Extensions.Hosting;+using Npgsql;/// <summary>-/// Admin web application factory fixture for integration tests.+/// Starts the Admin project in-memory on a temporary test database./// </summary>-/// <typeparam name="TEntryPoint">The entry point.</typeparam>-public class WebApplicationAdminFactoryFixture<TEntryPoint> : WebApplicationFactoryFixture<TEntryPoint>- where TEntryPoint : class+public class WebApplicationAdminFactoryFixture : WebApplicationFactory<AliasVault.Admin.Program>{+ /// <summary>+ /// The DbContextFactory instance that is created for the test.+ /// </summary>+ private IAliasServerDbContextFactory _dbContextFactory = null!;++ /// <summary>+ /// The cached DbContext instance that can be used during the test.+ /// </summary>+ private AliasServerDbContext? _dbContext;++ /// <summary>+ /// The name of the temporary test database.+ /// </summary>+ private string? _tempDbName;++ /// <summary>+ /// Whether UseKestrel has been called.+ /// </summary>+ private bool _kestrelConfigured;+/// <summary>/// Gets or sets the port the web application kestrel host will listen on./// </summary>- public override int Port { get; set; } = 5003;+ public int Port { get; set; }++ /// <summary>+ /// Returns the DbContext instance for the test. This can be used to seed the database with test data.+ /// </summary>+ /// <returns>AliasServerDbContext instance.</returns>+ public AliasServerDbContext GetDbContext()+ {+ _dbContext ??= _dbContextFactory.CreateDbContext();+ return _dbContext;+ }/// <summary>- /// Removes existing service registrations.+ /// Disposes the DbConnection instance and drops the temporary database./// </summary>- /// <param name="services">The <see cref="IServiceCollection"/> to modify.</param>- protected override void RemoveExistingRegistrations(IServiceCollection services)+ /// <returns>Task.</returns>+ public override async ValueTask DisposeAsync(){- var descriptorsToRemove = services.Where(d =>- d.ServiceType == typeof(VersionedContentService)).ToList();+ if (_dbContext != null)+ {+ await _dbContext.DisposeAsync();+ _dbContext = null;+ }- foreach (var descriptor in descriptorsToRemove)+ if (!string.IsNullOrEmpty(_tempDbName)){- services.Remove(descriptor);+ // Create a connection to 'postgres' database to drop the test database+ using var conn = new NpgsqlConnection("Host=localhost;Port=5109;Database=postgres;Username=aliasvault;Password=password");+ await conn.OpenAsync();++ // First terminate existing connections+ using (var cmd = conn.CreateCommand())+ {+ cmd.CommandText = $"""+ SELECT pg_terminate_backend(pid)+ FROM pg_stat_activity+ WHERE datname = '{_tempDbName}';+ """;+ await cmd.ExecuteNonQueryAsync();+ }++ // Then drop the database in a separate command+ using (var cmd = conn.CreateCommand())+ {+ cmd.CommandText = $"""+ DROP DATABASE IF EXISTS "{_tempDbName}";+ """;+ await cmd.ExecuteNonQueryAsync();+ }}++ GC.SuppressFinalize(this);+ await base.DisposeAsync();}/// <summary>- /// Adds new service registrations.+ /// Initializes the factory with Kestrel on the specified port.+ /// Must be called before CreateDefaultClient() in tests./// </summary>- /// <param name="services">The <see cref="IServiceCollection"/> to modify.</param>- protected override void AddNewRegistrations(IServiceCollection services)+ public void InitializeKestrel()+ {+ if (!_kestrelConfigured)+ {+ UseKestrel(Port);+ _kestrelConfigured = true;+ }+ }++ /// <inheritdoc />+ protected override IHost CreateHost(IHostBuilder builder)+ {+ var host = base.CreateHost(builder);++ // Get the DbContextFactory instance and store it for later use during tests.+ _dbContextFactory = host.Services.GetRequiredService<IAliasServerDbContextFactory>();++ return host;+ }++ /// <inheritdoc />+ protected override void ConfigureWebHost(IWebHostBuilder builder){- // Add the VersionedContentService- services.AddSingleton(new VersionedContentService("../../../../../AliasVault.Admin/wwwroot"));+ _tempDbName = $"aliasdb_test_{Guid.NewGuid()}";+ SetEnvironmentVariables();++ builder.ConfigureServices(services =>+ {+ var descriptorsToRemove = services.Where(d => d.ServiceType == typeof(VersionedContentService)).ToList();+ foreach (var descriptor in descriptorsToRemove)+ {+ services.Remove(descriptor);+ }++ services.AddSingleton(new VersionedContentService("../../../../../AliasVault.Admin/wwwroot"));- // Configure ServerSideBlazor with detailed errors- services.AddServerSideBlazor()- .AddCircuitOptions(options => options.DetailedErrors = true);+ // Configure ServerSideBlazor with detailed errors+ services.AddServerSideBlazor().AddCircuitOptions(options => options.DetailedErrors = true);+ });+ }++ /// <summary>+ /// Sets the required environment variables for testing.+ /// </summary>+ private void SetEnvironmentVariables()+ {+ Environment.SetEnvironmentVariable("ConnectionStrings__AliasServerDbContext", "Host=localhost;Port=5109;Database=" + _tempDbName + ";Username=aliasvault;Password=password");+ Environment.SetEnvironmentVariable("DATA_PROTECTION_CERT_PASS", "Development");+ Environment.SetEnvironmentVariable("ADMIN_PASSWORD_HASH", "AQAAAAIAAYagAAAAEKWfKfa2gh9Z72vjAlnNP1xlME7FsunRznzyrfqFte40FToufRwa3kX8wwDwnEXZag==");+ Environment.SetEnvironmentVariable("ADMIN_PASSWORD_GENERATED", "2024-01-01T00:00:00Z");+ Environment.SetEnvironmentVariable("ALIASVAULT_TEST_MODE", "true");}}diff --git a/apps/server/nginx-443.conf b/apps/server/nginx-443.confindex 96481fae7..0e7a3c794 100644--- a/apps/server/nginx-443.conf+++ b/apps/server/nginx-443.conf@@ -37,15 +37,14 @@ http {include /etc/nginx/mime.types;default_type application/octet-stream;- # Enable gzip compression, which reduces the amount of data that needs to be transferred- # to speed up WASM load times.+ # Enable gzip compression, which reduces the amount of data that needs to be transferred.gzip on;gzip_vary on;gzip_proxied any;gzip_comp_level 6;gzip_buffers 16 8k;gzip_http_version 1.1;- gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;+ gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript application/wasm;server {listen 80;diff --git a/apps/server/nginx-80-443.conf b/apps/server/nginx-80-443.confindex 873f70c95..94b748218 100644--- a/apps/server/nginx-80-443.conf+++ b/apps/server/nginx-80-443.conf@@ -37,15 +37,14 @@ http {include /etc/nginx/mime.types;default_type application/octet-stream;- # Enable gzip compression, which reduces the amount of data that needs to be transferred- # to speed up WASM load times.+ # Enable gzip compression, which reduces the amount of data that needs to be transferred.gzip on;gzip_vary on;gzip_proxied any;gzip_comp_level 6;gzip_buffers 16 8k;gzip_http_version 1.1;- gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;+ gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript application/wasm;server {listen 80;diff --git a/dockerfiles/all-in-one/config/nginx-443.conf b/dockerfiles/all-in-one/config/nginx-443.confindex c8e3e8074..694a539fd 100644--- a/dockerfiles/all-in-one/config/nginx-443.conf+++ b/dockerfiles/all-in-one/config/nginx-443.conf@@ -36,15 +36,14 @@ http {include /etc/nginx/mime.types;default_type application/octet-stream;- # Enable gzip compression, which reduces the amount of data that needs to be transferred- # to speed up WASM load times.+ # Enable gzip compression, which reduces the amount of data that needs to be transferred.gzip on;gzip_vary on;gzip_proxied any;gzip_comp_level 6;gzip_buffers 16 8k;gzip_http_version 1.1;- gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;+ gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript application/wasm;# HTTP server - redirects all traffic to HTTPSserver {diff --git a/dockerfiles/all-in-one/config/nginx-80-443.conf b/dockerfiles/all-in-one/config/nginx-80-443.confindex 8a5e3e265..8e1fdcd6c 100644--- a/dockerfiles/all-in-one/config/nginx-80-443.conf+++ b/dockerfiles/all-in-one/config/nginx-80-443.conf@@ -37,15 +37,14 @@ http {include /etc/nginx/mime.types;default_type application/octet-stream;- # Enable gzip compression, which reduces the amount of data that needs to be transferred- # to speed up WASM load times.+ # Enable gzip compression, which reduces the amount of data that needs to be transferred.gzip on;gzip_vary on;gzip_proxied any;gzip_comp_level 6;gzip_buffers 16 8k;gzip_http_version 1.1;- gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;+ gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript application/wasm;server {listen 80;